I have a subset of a SQL Server 2008 R2 table as follows:
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 different price periods as follows:
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 he sorts by cust_id , prod_id and day in ascending order, but increases the rank when the price changes. I tried using DENSE_RANK() as follows:
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 sorting will give me these results, but whenever I include the day in the order under the DENSE_RANK() section, it just breaks each new day into a new identifier ....
Does anyone have any ideas on how this should work? Please rate any advice and can provide more information if required.
source share