How can i use window functions to cover one column with another. But total value from one column?[b]Formula should go like this:[u][/u][/b][b][/b] sum(potr) = 160 dugu in 160 covered | [not covered] ------------------------- => 100 in 160 = 100 | 0 => 70 in 60 = 60 | 10 => 40 in 0 = 0 | 40 ---------------------------I have a table:[code="sql"] DECLARE @TEST TABLE ( id int, knt int, dt date, name VARCHAR(10), dugu decimal(18,2), potr decimal(18,2) ) [/code][code="sql"] INSERT INTO @TEST VALUES (1,2010001,'20150101','xxx',100, 0), (2,2010001,'20150201','yyy',70, 0 ), (3,2010001,'20150301','kkk',0, 60 ), (4,2010001,'20150401','aaa',40, 0 ), (5,2010001,'20150501','bbb',0, 70 ), (6,2010001,'20150601','ccc',0, 30 );[/code]I have made something like this:[code="sql"]with cte as ( Select id, knt, dt, name, POTR, DUGU, case when dugu > 0 then sum(potr) over() else 0 end as sumPotrAll, CASE WHEN DUGU = 0 THEN 0 ELSE sum(dugu) over (order by id rows between unbounded preceding and current row ) END as sumDuguByRow from @TEST ) select *, CASE WHEN sumPotrAll > sumDuguByRow and dugu <> 0 THEN dugu WHEN sumDuguByRow > sumPotrAll and dugu > 0 then sumPotrAll WHEN dugu = 0 and potr > 0 then 0 end as Covered from cte[/code]I have upload 2 pictures. One is my result and second is what i need to get[b]Sample at: [/b] http://sqlfiddle.com/#!6/c4783/1[b][/b]
↧