Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use group by with union in T-SQL

How can I using group by with union in T-SQL? I want to group by the first column of a result of union, I wrote the following SQL but it doesn't work. I just don't know how to reference the specified column (in this case is 1) of the union result.

SELECT  * FROM    ( SELECT    a.id ,                     a.time           FROM      dbo.a           UNION           SELECT    b.id ,                     b.time           FROM      dbo.b         ) GROUP BY 1 
like image 428
Just a learner Avatar asked Oct 22 '09 03:10

Just a learner


People also ask

Can you use GROUP BY with UNION?

There's no need to run GROUP BY on the contents when you're using UNION - UNION ensures that duplicates are removed; UNION ALL is faster because it doesn't - and in that case you would need the GROUP BY... There are use cases for wanting to use GROUP BY on the results of a union.

Can we use GROUP BY and count together in SQL?

We can use GROUP BY to group together rows that have the same value in the Animal column, while using COUNT() to find out how many ID's we have in each group. It returns a table with three rows (one for each distinct animal).

Do UNION SQL clause can be used with?

The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. But they need not have to be in the same length.


1 Answers

You need to alias the subquery. Thus, your statement should be:

Select Z.id From    (         Select id, time         From dbo.tablea         Union All         Select id, time         From dbo.tableb         ) As Z Group By Z.id 
like image 190
Thomas Avatar answered Sep 30 '22 23:09

Thomas