[英]SQL Server 2008 - ROWNUMBER OVER - filtering the result
I have the following SQL which works and returns products with duplicate names and the rownum column is a count of how many times that name appears. 我有以下SQL,该SQL可以正常工作并返回具有重复名称的产品,并且rownum列是对该名称出现多少次的计数。
Adding where rownum > 1
at the end gives me the duplicates only. 在最后添加
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
REQUIREMENT 需求
I need to produce a list of products where if the rownum column has a value greater than one, I want to see all the rows pertaining to that product grouped by the name column. 我需要生成一个产品列表,如果rownum列的值大于1,我想查看与该产品相关的所有行,并按名称列进行分组。
If the rownum value for a product is 1 only, and no value greater than one (so no duplicate) I don't want to see that row. 如果产品的rownum值仅为1,并且没有大于1的值(因此没有重复值),则我不希望看到该行。
So for example if "Blue umbrella" appears three times, I want to see the result for this product as: 因此,例如,如果“蓝伞”出现3次,我希望此产品的结果为:
ID Name Rownum
35 Blue umbrella 1
41 Blue umbrella 2
90 Blue umbrella 3
How would I go about achieving this please? 我将如何实现这一目标?
Change the Row_NUmber Over to Count(1) Over
and select where the count is greater than 1
and remove the group by 将
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.