我在MSSQL2005中有下表
id | business_key | result 1 | 1 | 0 2 | 1 | 1 3 | 2 | 1 4 | 3 | 1 5 | 4 | 1 6 | 4 | 0
现在我想根据business_key进行分组,返回id最高的完整条目.所以我的预期结果是:
business_key | result 1 | 1 2 | 1 3 | 1 4 | 0
我打赌有一种方法可以实现这一点,我现在看不到它.
另一种解决方案,可以为您提供更好的性能(测试两种方式并检查执行计划):
SELECT T1.id, T1.business_key, T1.result FROM dbo.My_Table T1 LEFT OUTER JOIN dbo.My_Table T2 ON T2.business_key = T1.business_key AND T2.id > T1.id WHERE T2.id IS NULL
此查询假定ID是唯一值(至少对于任何给定的business_key)并且它设置为NOT NULL.
select drv.business_key, mytable.result from mytable inner join ( select business_key, max(id) as max_id from mytable group by business_key ) as drv on mytable.id = drv.max_id