重複

2017-04-13 35 views
0

以下查詢顯示重複與數量別名表示總計數的表的增量計數,例如,如果有五個重複然後所有五個將具有相同的數量= 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

當'[日期]'和'[產品]'都相同時 – pathDongle

+0

您想要的輸出是什麼? – Teja

回答

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的某種組合幾乎肯定是您需要的。