重复的增量计数

时间:2017-04-13 20:03:44

标签: sql sql-server

以下查询在表格中显示重复项,其中qty别名显示总计数,例如,如果有五个重复项,那么所有五个将具有相同的qty = 5.

select s.*, t.* 
from [Migrate].[dbo].[Table1] s
join (
    select [date] as d1, [product] as h1, count(*) as qty
    from [Migrate].[dbo].[Table1]
    group by [date], [product]
    having count(*) > 1
) t on s.[date] = t.[d1] and s.[product] = t.[h1]
ORDER BY s.[product], s.[date], s.[id]

是否可以修改count(*) as qty以显示增量计数,以便五个重复显示1,2,3,4,5?

1 个答案:

答案 0 :(得分:1)

您的问题的答案是row_number()。您如何使用它尚不清楚,因为您没有提供指导,例如样本数据或所需结果。因此,这个答案相当普遍:

select s.*, t.*,
       row_number() over (partition by s.product order by s.date) as seqnum
from [Migrate].[dbo].[Table1] s join
     (select [date] as d1, [product] as h1, count(*) as qty
      from [Migrate].[dbo].[Table1]
      group by [date], [product]
      having count(*) > 1
     ) t
     on s.[date] = t.[d1] and s.[product] = t.[h1]
order by s.[product], s.[date], s.[id];

据推测,重复是按产品划分的。这按日期列举了它们。 partition bygroup by的某种组合几乎肯定是您所需要的。