这应该是一个简单的问题,但我不能让它起作用:(
如何选择具有最大列值的行,作为另一列的组?
例如,
我有以下表格定义:
ID
Del_Index
docgroupviewid
现在的问题是,我希望先按docgroupviewid
按结果对结果进行分组,然后从每个docgroupviewid
组中选择一行,具体取决于哪一行具有最高del_index
。< / p>
我试过
SELECT docgroupviewid, max(del_index),id FROM table
group by docgroupviewid
但是,不是使用正确的id
返回给我,而是返回具有相同id
的群组中最早的docgroupviewid
。
有什么想法吗?
答案 0 :(得分:9)
我自己多次努力,解决方案是以不同的方式考虑您的查询。
我想要每个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 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
。
答案 1 :(得分:3)
您必须稍微复杂一下您的查询:
select a.docgroupviewid, a.del_index, a.id from table a
where a.del_index = (select max(b.del_index) from table
where b.docgroupviewid = a.docgroupviewid)