UNION ALL sur 2 tables sélectionner avec Cases

Je cours SQL Server 2005. J'ai 2 tables avec les mêmes colonnes mais tenant des données très différentes.

SELECT * FROM Table1 WHERE ItemID IN ('4','2','1') ORDER BY CASE WHEN ItemID = 4 then 1 WHEN ItemID = 2 then 2 WHEN ItemID = 1 then 3 END UNION ALL SELECT * FROM Table2 WHERE ItemID IN ('3','1','5','2') ORDER BY CASE WHEN ItemID = 3 then 4 WHEN ItemID = 1 then 5 WHEN ItemID = 5 then 6 WHEN ItemID = 2 then 7 END 

J'ai besoin de garder l'ordre de l' ItemID dans l'ordre où ils sont sélectionnés, c'est pourquoi j'ai utilisé CASE . Tout cela fonctionne bien sur chaque table mais je ne trouve pas un moyen de les combiner en 1 table de résultats avec les résultats de chaque table commandée.

c'est à dire

 4 (Table1) 2 (Table1) 1 (Table1) 3 (Table2) 1 (Table2) 5 (Table2) 2 (Table2) 

Extrêmement reconnaissant pour toute aide.

Vous pouvez utiliser la requête suivante:

 SELECT Table1.* , x.[Order] AS Ord FROM Table1 CROSS APPLY (SELECT CASE ItemID WHEN 4 THEN 1 WHEN 2 THEN 2 WHEN 1 THEN 3 END) x([Order]) WHERE ItemID IN ('4','2','1') UNION ALL SELECT Table2.* , y.[Order] AS Ord FROM Table2 CROSS APPLY (SELECT CASE ItemID WHEN 3 THEN 4 WHEN 1 THEN 5 WHEN 5 THEN 6 WHEN 2 THEN 7 END) y([Order]) WHERE ItemID IN ('3','1','5','2') ORDER BY Ord 

Champ calculé [Order] garantit que les loggings de Table1 viendront en premier, suivis par les loggings de Table2 . Il assure également la command dans chaque partition Table1 ou Table2 .

Démo ici

Ceci est une syntaxe alternative sans l'utilisation de CROSS APPLY :

 SELECT Table1.*, CASE ItemID WHEN 4 THEN 1 WHEN 2 THEN 2 WHEN 1 THEN 3 END AS Ord FROM Table1 WHERE ItemID IN ('4','2','1') UNION ALL SELECT Table2.*, CASE ItemID WHEN 3 THEN 4 WHEN 1 THEN 5 WHEN 5 THEN 6 WHEN 2 THEN 7 END AS Ord FROM Table2 WHERE ItemID IN ('3','1','5','2') ORDER BY Ord 

Démo ici

Essaye ça:

 SELECT * FROM ( SELECT * , 1 as ord FROM Table1 WHERE ItemID IN (4, 2, 1) UNION ALL SELECT * , 2 as ord FROM Table2 WHERE ItemID IN (3, 1, 5, 2) ) t ORDER BY ord, CASE WHEN ItemID = 3 then 4 WHEN ItemID = 1 then 5 WHEN ItemID = 5 then 6 WHEN ItemID = 2 then 7 END, CASE WHEN ItemID = 4 then 1 WHEN ItemID = 2 then 2 WHEN ItemID = 1 then 3 END 

Ou

 SELECT *, ROW_NUMBER() OVER (ORDER BY ord, CASE WHEN ItemID = 3 then 4 WHEN ItemID = 1 then 5 WHEN ItemID = 5 then 6 WHEN ItemID = 2 then 7 END, CASE WHEN ItemID = 4 then 1 WHEN ItemID = 2 then 2 WHEN ItemID = 1 then 3 END) as RowNo FROM ( SELECT * , 1 as ord FROM Table1 WHERE ItemID IN (4, 2, 1) UNION ALL SELECT * , 2 as ord FROM Table2 WHERE ItemID IN (3, 1, 5, 2) ) t