Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

TSQL dense rank type question - finding the first date of a budget change (budget values can bounce back and forth in values)

$
0
0
I am trying to write a query to give me all "budget changes" (and the day they happened) per customer. Example is below:create table testTable(id tinyint NOT NULL, cust_id int NOT NULL, sDate datetime NOT NULL, budget DECIMAL(8,2) NOT NULL);INSERT INTO testTable (id,cust_id,sDate,budget) VALUES (1,1,'2015-01-01',100);INSERT INTO testTable (id,cust_id,sDate,budget) VALUES(2,1,'2015-02-01',100);INSERT INTO testTable (id,cust_id,sDate,budget) VALUES(9,1,'2015-03-01',500);INSERT INTO testTable (id,cust_id,sDate,budget) VALUES(4,1,'2015-04-01',100);INSERT INTO testTable (id,cust_id,sDate,budget) VALUES (3,2,'2015-01-01',50);INSERT INTO testTable (id,cust_id,sDate,budget) VALUES(7,2,'2015-02-01',10);INSERT INTO testTable (id,cust_id,sDate,budget) VALUES(5,2,'2015-03-01',50);INSERT INTO testTable (id,cust_id,sDate,budget) VALUES(8,2,'2015-04-01',50);Which looks like this:select * from testTable order by cust_id,sDate;id cust_id sDate budget1 1 2015-01-01 100.002 1 2015-02-01 100.009 1 2015-03-01 500.004 1 2015-04-01 100.003 2 2015-01-01 50.007 2 2015-02-01 10.005 2 2015-03-01 50.008 2 2015-04-01 50.00Desired output: (Give me all records that reflect budget changes from the previous period) which is rows: 1,9,4,3,7,5 cust_id sDate Budget1 2015-01-01 100 1 2015-03-01 5001 2015-04-01 1002 2015-01-01 502 2015-02-01 102 2015-03-01 50 My best guess is:SELECT cust_Id,sDate,budget FROM (select cust_id,sDate,budget, DENSE_RANK() OVER (PARTITION BY cust_id,budget ORDER BY cust_id,sDate asc,budget) drfrom testTable ) inlineT WHERE dr=1 order by 1,2;Which actually returns me incorrect results because the dense rank does not restart due to the budget change :cust_id sDate budget1 2015-01-01 100.001 2015-03-01 500.002 2015-02-01 10.002 2015-01-01 50.00

Viewing all articles
Browse latest Browse all 3145

Trending Articles