简体   繁体   中英

SQL generate sequential id's based on other column(s)

Probably best I explain what I'm after with an example :)

Say I have the following table

SELECT *
INTO #OrderRanking
FROM (
    SELECT 'Jim', 1000
    UNION ALL
    SELECT 'Jim', 500
    UNION ALL
    SELECT 'Jim', 500
    UNION ALL
    SELECT 'Jim', 3000
    UNION ALL
    SELECT 'Bob', 1000
    UNION ALL
    SELECT 'Bob', 2000
    UNION ALL
    SELECT 'Bob', 500
    UNION ALL
    SELECT 'Bob', 500
    UNION ALL
    SELECT 'Fred', 500
) AS t(Customer, OrderTotal)

What I want is the following result in a SELECT statement

Customer, OrderTotal, CustomerId
'Jim', 1000, 1
'Jim', 500, 1
'Jim', 500, 1
'Jim', 3000, 1
'Bob', 1000, 2
'Bob', 2000, 2
'Bob', 500, 2
'Bob', 500, 2
'Fred', 500, 3

My actual query is a bit more complex, where the source columns is more than 2.

I am a pillock,

SELECT *, DENSE_RANK() OVER(ORDER BY Customer DESC)
FROM #OrderRanking

I think this should cover all cases!

select customer, ordertotal, dense_rank() over(order by total desc, customer asc)
from (select *, sum(ordertotal) over(partition by customer) total from  #orderranking) t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM