How to put a counter in Group By Customer

2019-02-25 20:25发布

问题:

They're the same column

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

now in my script, i group them in Category but i want to count on how many times they occur in the query. please see below:

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)

sorry for confusion, hope its clear for everyone.

Thank you,

回答1:

You can use row_number() to add a number to customers with the same name:

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

If the number is only required if there is more than one customer, you can use a case when ... then ... end expression:

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.