2

请参考以下脚本

            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    | 
            ---------------

如果是这样,你能帮我查询一下吗?

谢谢,埃森。

4

3 回答 3

3

试试这个:

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

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

于 2012-11-02T21:25:17.817 回答
3

SQL小提琴

      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 |
于 2012-11-02T21:26:01.980 回答
1
select *, rn=row_number() over (partition by col1 order by col1 )
  from @table1
于 2012-11-02T21:28:51.440 回答