我理解这个问题的一些变种已被问到,但我找不到我的具体情况的答案。
我的查询有超过50个字段被选中,其中只有一个是聚合,使用MAX()。在GROUP BY子句中,我只想传递两个特定字段,name和UserID,而不是全部50个以使查询运行。请参阅下面的小部分。
SELECT
t1.name,
MAX(t2.id) as UserID,
t3.age,
t3.height,
t3.dob,
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
LEFT JOIN table3 t3 ON t1.id = t3.id
GROUP BY t1.name, UserID
是否有任何解决方法或更好的方法来实现我的目标? 数据库是SQL Server,非常感谢任何帮助。
答案 0 :(得分:4)
max()
和id
有一列的code
,则可以执行以下操作:
select t.*
from (select t.*, max(col) over (partition by id, code) as maxcol
from t
) t
where col = maxcol;
鉴于id
可能是唯一的,您可能需要最大id
以及每个code
的其他列:
select t.*
from (select t.*, max(id) over (partition by code) as maxid
from t
) t
where id = maxid;