T sql找到相同的值并按顺序排序

时间:2015-04-10 09:53:12

标签: sql-server

我有这些列的表Customer

sales_ID varchar(50)
product_ID int
ProcessNumber int
CreateDate datetime

以及此示例数据:

sales_Id       product_id    ProcessNumber
---------------------------------------------  
00000020041       1733           15
00000020041       1733           15    
00000020041       1733           15

问题:

如果我使用此查询

select * 
from 
    (select 
        *,
        row_number() over(PARTITION BY sales_Id, product_ID, ProcessNumber
                          ORDER BY xdate) rown
     from Customer) tbl 
where 
     rown > 1 
order by 
     sales_ID

结果:

1. 00000020041      1733       15

但我希望查询显示此结果

 1. 00000020041      1733       15
 2. 00000020041      1733       15
 3. 00000020041      1733       15

根据选择所有重复值(2行,3行,4行......)在我的查询中要更改什么?

2 个答案:

答案 0 :(得分:3)

ROW_NUMBER() OVER()更改为COUNT(*) OVER(),例如

SELECT  *
FROM    (   SELECT  *,
                    CountOfRowsInGroup = COUNT(*) OVER (
                        PARTITION BY sales_Id,product_ID,ProcessNumber)
            FROM    Customer
        ) AS tbl
WHERE   CountOfRowsInGroup > 1
ORDER BY Sales_ID;

这将返回所有重复项

答案 1 :(得分:0)

查找RANK和DENSE_RANK。我最好改写它,因为它有误导性:如果你有3个重复的RANK记录可能编号为1,1,1,4,5,6等。如果你有3个重复的DENSE_RANK你会得到1,1,1,2 ,3,4等。