Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
How to GROUP BY in a UNION
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Divers
Thread ID:
00893344
Message ID:
00893427
Vues:
16
Michael,

The name of the columns don't have to be the same in UNION SELECT's. The problem is that the GROUP BY clause belongs to the particular select not to the result of UNION. You can use derived table to get around it
SELECT cItemNo, cWareHouse, 
		SUM(nReturned) AS nReturned, SUM(nShipped) AS nShipped
FROM 		
	SELECT     citemno1 AS cItemNo, cWhouse1 AS cWareHouse, 
			SUM(ntrfqty1) AS nReturned, SUM(0000000000) AS nShipped
		FROM         icitrf
		WHERE     (dtrs BETWEEN '03/18/04' AND '03/25/04') 
                                AND (cwhouse1 BETWEEN 'X0000' AND 'X9999')
		GROUP BY 1, 2
	UNION
	SELECT   citemno2 AS cItemNo, cWhouse2 AS cWareHouse, 
			SUM(0000000000) AS nReturned, SUM(ntrfqty2) AS nShipped
		FROM  icitrf
		WHERE     (dtrs BETWEEN '03/18/04' AND '03/25/04') 
                               AND (cwhouse2 BETWEEN 'X0000' AND 'X9999')
		GROUP BY 1, 2) dt
GROUP BY 1, 2
>I have a UNION with different souce names for my grouped fields, so SQL is complaining.
>
>Can I do this in one statement, or will I have to create intermediate tables to do this?
>
>
>SELECT     citemno1 AS cItemNo, cWhouse1 AS cWareHouse, 
SUM(ntrfqty1) AS nReturned, 0000000000 AS nShipped
>FROM         icitrf
>WHERE     (dtrs BETWEEN '03/18/04' AND '03/25/04') 
AND (cwhouse1 BETWEEN 'X0000' AND 'X9999')
>UNION
>SELECT     citemno2 AS cItemNo, cWhouse2 AS cWareHouse, 
0000000000 AS nReturned, SUM(ntrfqty2) AS nShipped
>FROM         icitrf
>WHERE     (dtrs BETWEEN '03/18/04' AND '03/25/04') AND (cwhouse2 BETWEEN 'X0000' AND 'X9999')
>GROUP BY 1, 2
>
>
>TIA
--sb--
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform