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
GROUP BY
on the results of a union. In the example given, you may way the most recent time for each ID, whether that time is in TABLE_A or TABLE_B. You'd need aGROUP BY
with MAX(time) to achieve that. – Triumph