简体   繁体   中英

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.

Adding where rownum > 1 at the end gives me the duplicates only.

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.

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.

So for example if "Blue umbrella" appears three times, I want to see the result for this product as:

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

SELECT * from (Select id,productname,
        Count(1) OVER(Partition By productname ORDER by productname) Rownum
            FROM products 
            ) result 
        WHERE Rownum > 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM