I have a subset of a SQL Server 2008 R2 table like this:
cust_id | prod_id | day | price
--------+---------+-----+-------
137656 194528 42373 9.11
137656 194528 42374 9.11
137656 194528 42375 9.61
137656 194528 42376 9.61
137656 194528 42377 9.11
137656 194528 42378 9.11
I need to rank the different price periods like so:
cust_id | prod_id | day | price | rank
--------+---------+-----+-------+------
137656 194528 42373 9.11 1
137656 194528 42374 9.11 1
137656 194528 42375 9.61 2
137656 194528 42376 9.61 2
137656 194528 42377 9.11 3
137656 194528 42378 9.11 3
so that it sorts by cust_id
, prod_id
and day
ascending but increments the rank when the price changes. I have tried to use DENSE_RANK()
like this:
SELECT
cust_id, prod_id, [day], price,
DENSE_RANK() OVER (ORDER BY cust_id, prod_id, price)
FROM
@prices
This returns something like:
cust_id | prod_id | day | price | rank
--------+---------+-----+-------+------
137656 194528 42373 9.11 1
137656 194528 42374 9.11 1
137656 194528 42377 9.11 1
137656 194528 42378 9.11 1
137656 194528 42375 9.61 2
137656 194528 42376 9.61 2
Obviously excluding the day from the sort will give me these results but whenever I include the day in the order by section of the DENSE_RANK()
- it just partitions each new day as a new ID....
Does anyone have any ideas on how this should work? Appreciate any advice and can give more info if required