如何通过使用SQL将计数器放入组中

时间:2014-09-02 06:27:06

标签: sql

我在下面有两列相应的数据:

Name    Category
A       SL
B       SL
C       SL
A       SL
A       SL
C       SL

现在在我的脚本中,我将它们分组到类别中以了解计数器发生了多少次:

select Name, count(*) from Customer
group by Category

但我想依靠它们在查询中出现的次数如下:

Customer    Number#
A           1 (means its the first time it occurs)
A           2 (means its the second time it occurs)
A           3 (means its the third time it occurs)

....等等

B           1 (means its the first time it occurs)
C           1 (means its the first time it occurs)
C           2 (means its the second time it occurs)
抱歉混淆,希望每个人都清楚。

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试以下查询: -

SELECT name + '-' + CAST(ROW_NUMBER() OVER (
            PARTITION BY NAME ORDER BY id) AS VARCHAR(24))
FROM YOUR_TABLE