Use Access SQL to do a grouped ranking

后端 未结 6 707
悲哀的现实
悲哀的现实 2020-11-29 12:26

How do I rank salespeople by # customers grouped by department (with ties included)?

For example, given this table, I want to create the Rank column on the

6条回答
  •  死守一世寂寞
    2020-11-29 12:41

    You need to do some math. I typically take advantage of the combination of a counter field and an "offset" field. You're aiming for a table which looks like this (#Customers isn't necessary, but will give you a visual that you're doing it properly):

    SalesPerson Dept #Customers Ctr Offset
    Bill        DeptA     20    1   1
    Ted         DeptA     30    2   1
    Jane        DeptA     40    3   1
    Bill        DeptB     50    4   4
    Mary        DeptB     60    5   4
    

    So, to give rank, you'd do [Ctr]-[Offset]+1 AS Rank

    1. build a table with SalesPerson, Dept, Ctr, and Offset
    2. insert into that table, ordered by Dept and #Customers (so that they're all sorted properly)
    3. Update Offset to be the MIN(Ctr), grouping on Dept
    4. Perform your math calculation to determine Rank
    5. Clear out the table so you're ready to use it again next time.

提交回复
热议问题