Group by Union Query (1 Viewer)

Tskutnik

Registered User.
Local time
Today, 04:11
Joined
Sep 15, 2012
Messages
229
Quick one - I'm a newbie. The following Group by logic is not working. What am I missing?.
Thanks for the help. I'm sure it is a semi-colon or something in the wrong place.

Code:

SELECT
Sec_Key,
Sec_SourceKey
FROM SecurityMaster_Source

UNION ALL Select
Sec_Key,
Sec_SourceKey
FROM SecurityMaster_Enhanced

GROUP BY [Sec_Key], [Sec_SourceKey];

Result....

The output is not grouping. There 2 matching rows in the underling 2 tables and they are both showing (duplicated and not grouped) in the output.
 

pbaldy

Wino Moderator
Staff member
Local time
Today, 01:11
Joined
Aug 30, 2003
Messages
36,125
The GROUP BY clause is only be applied to the second SELECT statement; each stands alone. Have you tried UNION instead of UNION ALL? UNION alone eliminates duplicates.
 

plog

Banishment Pending
Local time
Today, 03:11
Joined
May 11, 2011
Messages
11,646
A UNION should query should just bring data together. No grouping, no criteria, no calculations:
Code:
SELECT * FROM A
UNION SELECT * FROM B

When you need to GROUP, or apply criteria or make calculated fields you do that in another query based on the UNION:

Code:
SELECT Field1, SUM(Field2) AS Total
FROM UnionQuery
GROUP BY Field1
 

pbaldy

Wino Moderator
Staff member
Local time
Today, 01:11
Joined
Aug 30, 2003
Messages
36,125
All true, but in this case just dropping ALL should return the desired result.
 

Tskutnik

Registered User.
Local time
Today, 04:11
Joined
Sep 15, 2012
Messages
229
Got it - both responses were helpful, thanks
 

Users who are viewing this thread

Top Bottom