2012-03-29 88 views
1

我有一個表ProductNumberDuplicates_backups,它有兩列名爲ProductID和ProductNumber。有一些重複的ProductNumbers。我如何計算不同數量的產品,然後打印出結果,如「()產品是備份的。」 ?因爲這是在一個存儲過程中,所以我必須使用一個變量@numrecord作爲不同的行數。我把我的代碼是這樣的:T-SQL如何計算重複行數然後打印結果?

set @numrecord= select distinct ProductNumber 
from ProductNumberDuplicates_backups where COUNT(*) > 1 
group by ProductID 
having Count(ProductNumber)>1 
Print cast(@numrecord as varchar)+' product(s) were backed up.' 

顯然錯誤是在=符號之後,因爲select不能跟着它。我搜索類似的案例,但他們只是選擇語句。請幫忙。非常感謝!

回答

1

嘗試

select @numrecord= count(distinct ProductNumber) 
from ProductNumberDuplicates_backups 
Print cast(@numrecord as varchar)+' product(s) were backed up.' 
+0

謝謝您!這工作和簡單 – 2012-03-29 06:46:45

1
begin tran 
create table ProductNumberDuplicates_backups (
    ProductNumber int 
) 

insert ProductNumberDuplicates_backups(ProductNumber) 
    select 1 
    union all 
    select 2 
    union all 
    select 1 
    union all 
    select 3 
    union all 
    select 2 

select * from ProductNumberDuplicates_backups 

declare @numRecord int 

select @numRecord = count(ProductNumber) from 
    (select ProductNumber, ROW_NUMBER() 
     over (partition by ProductNumber order by ProductNumber) RowNumber 
from ProductNumberDuplicates_backups) p 
where p.RowNumber > 1 

print cast(@numRecord as varchar) + ' product(s) were backed up.' 
rollback 
+0

謝謝,但打印線顯示28個產品,這是4比我實際expected.'' – 2012-03-29 06:38:53

相關問題