如何在Group By Customer中放置一个计数器

时间:2014-09-02 04:38:15

标签: sql sql-server tsql

他们是同一列

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

现在在我的脚本中,我将它们分组到类别中,但我想指望它们在查询中出现的次数。请看下面:

Customer-Line#
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)
....so on
----------
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 :(得分:5)

您可以使用row_number()向具有相同名称的客户添加号码:

select  name + '-' + cast(row_number() over (
            partition by name order by id) as varchar(24))
from    YourTable

如果只有多个客户才需要该号码,您可以使用case when ... then ... end表达式:

select  name + 
            case 
            when count(*) over (partition by name) = 1 then ''
            else '-' + cast(row_number() over (
                partition by name order by id) as varchar(24))
            end
from    YourTable

Example at SQL Fiddle.