自定义查询以显示具有重复计数及其重复出现的记录

时间:2012-11-02 21:22:32

标签: sql sql-server

请参阅以下脚本

            declare @table1 table
            (
            col1 int
            )  

            insert into @table1 values(1)
            insert into @table1 values(3)
            insert into @table1 values(3)
            insert into @table1 values(6)
            insert into @table1 values(4)
            insert into @table1 values(4)
            insert into @table1 values(4) 

以下查询提供

            select col1 ,COUNT(col1) cntCol1 from @table1 group by col1

此输出

            ----------------
            col1   | cntCol1
            -------| -------
            | 1    | 1    | 
            | 3    | 2    | 
            | 4    | 3    | 
            | 6    | 1    | 
            ---------------

是否可以获得以下输出

            ----------------
            col1   | cntCol1
            -------| -------
            | 1    | 1    | 
            | 3    | 1    | 
            | 3    | 2    |  
            | 4    | 1    |  
            | 4    | 2    |  
            | 4    | 3    | 
            | 6    | 1    | 
            ---------------

如果是这样,请你帮我查询一下。

谢谢, 也先。

3 个答案:

答案 0 :(得分:3)

试试这个:

select 
    col1, 
    Sequence = ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col1)
from 
    @table1 

对于数据的每个“分区”,ROW_NUMBER()函数从1开始连续输出数字(在您的情况下:对于表中col1的每个不同值)

答案 1 :(得分:3)

SQL Fiddle

      SELECT col1, ROW_NUMBER() OVER (partition by col1 order by col1) cntCol1
        FROM @table1
    ORDER BY col1, cntCol1    

示例数据

 declare @table1 table
            (
            col1 int
            )  

            insert into @table1 values(1)
            insert into @table1 values(3)
            insert into @table1 values(3)
            insert into @table1 values(6)
            insert into @table1 values(4)
            insert into @table1 values(4)
            insert into @table1 values(4) 

<强>结果:

| COL1 | CNTCOL1 |
------------------
|    1 |       1 |
|    3 |       1 |
|    3 |       2 |
|    4 |       1 |
|    4 |       2 |
|    4 |       3 |
|    6 |       1 |

答案 2 :(得分:1)

select *, rn=row_number() over (partition by col1 order by col1 )
  from @table1