这应该是一个简单的问题,但我不能让它工作:(
如何选择具有最大列值的行,作为另一列的组?
例如,
我有以下表定义:
ID Del_Index docgroupviewid
现在的问题是我想先按docgroupviewid按结果分组,然后从每个docgroupviewid组中选择一行,具体取决于哪一行具有最高的del_index.
我试过了
SELECT docgroupviewid,max(del_index),id FROM table group by docgroupviewid
但是不是使用正确的ID返回给我,而是返回具有相同docgroupviewid的组中最早的id.
有任何想法吗?
解决方法
我自己多次努力,解决方案是以不同的方式考虑你的查询.
我想要每个DocGroupViewID行,其中Del_Index是具有该DocGroupViewID的所有行的最高(最大):
SELECT T.DocGroupViewID,T.Del_Index,T.ID FROM MyTable T WHERE T.Del_Index = ( SELECT MAX( T1.Del_Index ) FROM MyTable T1 WHERE T1.DocGroupViewID = T.DocGroupViewID )
当多个行可以具有相同的Del_Index时,它会变得更复杂,因为那时您需要某种方式来选择要显示的行.
编辑:想跟进另一个选项
您可以将RANK()或ROW_NUMBER()函数与CTE一起使用,以获得对结果的更多控制,如下所示:
-- fake a source table DECLARE @t TABLE ( ID int IDENTITY(1,1) PRIMARY KEY,Del_Index int,DocGroupViewID int ) INSERT INTO @t SELECT 1,1 UNION ALL SELECT 2,1 UNION ALL SELECT 3,1 UNION ALL SELECT 1,2 UNION ALL SELECT 2,2 UNION ALL SELECT 1,3 UNION ALL SELECT 2,3 UNION ALL SELECT 3,3 UNION ALL SELECT 4,3 -- show our source SELECT * FROM @t -- select using RANK (can have duplicates) ;WITH cteRank AS ( SELECT DocGroupViewID,Del_Index,ID,RANK() OVER (PARTITION BY DocGroupViewID ORDER BY Del_Index DESC) AS RowRank,ROW_NUMBER() OVER (PARTITION BY DocGroupViewID ORDER BY Del_Index DESC) AS RowNumber FROM @t ) SELECT * FROM cteRank WHERE RowRank = 1 -- select using ROW_NUMBER ;WITH cteRowNumber AS ( SELECT DocGroupViewID,ROW_NUMBER() OVER (PARTITION BY DocGroupViewID ORDER BY Del_Index DESC) AS RowNumber FROM @t ) SELECT * FROM cteRowNumber WHERE RowNumber = 1