Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
How to GROUP BY in a UNION
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
00893344
Message ID:
00893427
Views:
19
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--
Previous
Reply
Map
View

Click here to load this message in the networking platform