这应该是一个简单的问题,但我无法使其起作用:(
如何按另一列分组选择具有最大列值的行?
例如,
我有以下表格定义:
ID Del_Index docgroupviewid
现在的问题是,我想先按结果分组docgroupviewid,然后再从每组中选择一行docgroupviewid,具体取决于哪一组具有最高的del_index。
docgroupviewid
del_index
我试过了
SELECT docgroupviewid, max(del_index),id FROM table group by docgroupviewid
但是,与其以正确的方式id回报我,不如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,因为从那时起,您需要某种方式来选择要显示的行。
Del_Index
您可以将RANK()或ROW_NUMBER()函数与CTE结合使用,以更好地控制结果,如下所示:
RANK()
ROW_NUMBER()
-- 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 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, 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 cteRowNumber WHERE RowNumber = 1
如果您有办法解决领带,只需将其添加到中ORDER BY。
ORDER BY