如何在SQL中获取每个组的第一个最高结果

问题描述 投票:0回答:1

我正在使用这个SQL查询,我想获取每组的第一条记录。我已经使用了

ROW_NUMBER()
功能,但它仍然显示每个组的所有记录。谁能指导我正确的方向来实现我的输出?

    WITH CTE_SUM AS 
(
    SELECT 
        FA.AuditIntID, FA.FileIntID, 
        MAX(FA.AuditDate) AS Auditdaa,  
        ROW_NUMBER() OVER (PARTITION BY FA.AuditIntID ORDER BY FA.AuditIntID DESC) AS rn
    FROM  
        DBO.Audit FA WITH (NOLOCK)
    WHERE
        FA.FirmIntID = 1 
    GROUP BY 
        FA.AuditIntID, FA.FileIntID
)
SELECT 
    CS.AuditIntID, MDC.EntityIntID, CS.Auditdaa,
    CS.fileintid, cs.rn 
FROM
    CTE_SUM CS WITH (NOLOCK)
INNER JOIN  
    [DBO].[Meta] MDC ON MDC.FileIntID = CS.FileIntID 
WHERE 
    rn = 1
ORDER BY
    MDC.EntityIntID,CS.Auditdaa DESC

下面是我的示例表数据,在表中我只想检索每组的第一行。例如,在表中您可以看到(fileintid = 160051)和第二个(fileintid = 320072)想要在结果中看到等等......这是每组的第一行作为我的结果行。我可以看到每个

row_number
在输出结果数据中显示相同值的问题。

审核表示例数据

审计内部ID 文件ID 审核日期 描述 详情 结果 交易
10002 10002 11/8/22 9:31 测试1 测试1 T 添加
10003 10003 11/8/22 9:51 测试2 测试2 T 添加
10004 10004 11/8/22 9:54 测试3 测试3 T 添加
10005 10005 11/8/22 10:36 测试4 测试4 T 添加
10006 10006 11/8/22 12:00 测试5 测试5 T 添加
10007 10007 11/8/22 12:05 测试6 测试6 T 添加

元表示例数据

文件ID 实体类型 EntityIntID 文件ID
10002 C 2 4
10003 C 1 5
10004 C 2 6
10005 C 2 7
10006 C 2 8
10007 C 1 9

输出结果

EntityIntID 审计达 文件ID rn
1 7/28/23 12:53 160051 1
1 7/27/23 9:49 380075 1
1 23/6/27 10:06 310073 1
1 23年6月27日 9:48 310073 1
1 23年6月27日 9:48 310073 1
1 23年6月27日 9:46 310073 1
2 7/4/23 5:42 320072 1
2 23年6月27日11:25 310074 1
2 23/6/27 11:24 310074 1
2 23/6/27 11:23 140050 1
2 23/6/27 10:43 310074 1
2 23/6/27 10:43 310074 1
2 23/6/27 10:43 310074 1
2 23年6月27日 9:44 310072 1
2 23/6/26 19:15 300073 1
2 23/6/26 19:13 300073 1
2 23/6/26 19:12 300073 1
2 23/6/26 19:09 120036 1
2 23/6/26 19:09 300073 1
2 23/6/26 19:09 300073 1
2 23/6/26 19:08 300073 1
2 23/6/26 19:08 120036 1

预期上述查询的输出如下,下面显示每组每行的第一个记录。

EntityIntID 审计达 文件ID rn
1 7/28/23 12:53 160051 1
2 7/4/23 5:42 320072 1
sql database group-by row-number
1个回答
0
投票

尚不清楚为什么在查询中使用行聚合 (

GROUP BY
/
MAX
)。在您的任务描述中,您没有提及任何有关聚合的内容,您只想选择某些行,仅此而已。这就是您查询中的
ROW_NUMBER
的用途。

您希望每个entityintid有一个结果行,因此在对行进行编号时请使用按entityintid进行分区。

select entityintid, auditdate, fileintid
from
(
  select
    m.entityintid,
    cs.auditdate,
    m.fileintid,
    row_number() over (partition by m.entityintid order by cs.auditintid desc) as rn
  from [DBO].[Meta] m
  join cte_sum cs on cs.fileintid = m.fileintid
) with_rn
where rn = 1
order by entityintid;
© www.soinside.com 2019 - 2024. All rights reserved.