You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL查询:筛选BK_Vendedor重复值并取每组最小BeginDate行

enter image description here

直接在子查询里加一个ROW_NUMBER()窗口函数即可:按BK_Vendedor分区,分区内按BeginDate从小到大排序生成行号,外层筛选时同时保留「BK_Vendedor存在重复」+「分组内行号为1(即BeginDate最小)」的记录,修改后的代码如下:

SELECT [BK_Vendedor]
       ,[NIF]
      ,[BeginDate]
      ,[EndDate]
FROM (
      select 
       [BK_Vendedor]
      ,[NIF]
      ,[BeginDate]
      ,[EndDate],
             count(*) over (partition by [BK_Vendedor]) as dc,
             row_number() over (partition by [BK_Vendedor] order by [BeginDate] asc) as rn
      from [test_SA].[dbo].[Dim_Vendedor]
     ) as T
where dc > 1
  and rn = 1

注意事项

  • 如果同一个BK_Vendedor分组下有多条记录的BeginDate同为最小值,上述写法只会返回其中1条;需要返回所有同值最小记录的话,把row_number()替换为rank()即可。
  • 大表查询场景下,可以给BK_Vendedor、BeginDate建立联合索引,能明显提升查询效率。

内容的提问来源于stack exchange,提问作者rafamaniac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 23:36:35