[英]SQL Server 2008 - ROWNUMBER OVER - filtering the result
我有以下SQL,該SQL可以正常工作並返回具有重復名稱的產品,並且rownum列是對該名稱出現多少次的計數。
在最后添加where rownum > 1
,只給我重復的地方。
SELECT *
FROM
(SELECT
id, productname,
ROW_NUMBER() OVER (PARTITION BY productname
ORDER BY productname) Rownum
FROM products
GROUP BY id, productname) result
需求
我需要生成一個產品列表,如果rownum列的值大於1,我想查看與該產品相關的所有行,並按名稱列進行分組。
如果產品的rownum值僅為1,並且沒有大於1的值(因此沒有重復值),則我不希望看到該行。
因此,例如,如果“藍傘”出現3次,我希望此產品的結果為:
ID Name Rownum
35 Blue umbrella 1
41 Blue umbrella 2
90 Blue umbrella 3
我將如何實現這一目標?
將Row_NUmber Over to Count(1) Over
更改Row_NUmber Over to Count(1) Over
然后select where the count is greater than 1
然后按以下方式刪除組
SELECT * from (Select id,productname,
Count(1) OVER(Partition By productname ORDER by productname) Rownum
FROM products
) result
WHERE Rownum > 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.