declare @checksent int = 40
;with src
as
(
select *,
case
when @checksent < ot2 then 0
else @checksent - ot2
end as left_over
from @t
)
select *,
case
when t.ot1 < left_over then 0
else t.ot1 - left_over
end as left_over
from @t t
join src on t.id = src.id
doing this SQL is the very easy easy part !!
first understanding what to do is the only difficult part .. !!
You may understand it perfectly
[ But the main skill is how to explain it to others In very very very simple ways .. ]
[so that they can understand you very easily ]
this is my area of interest !!! i like these sort of things VERY VERY Much
but that's me
and THEN help you
otherwise ENDLESS back and forth back and forth
(
But the main skill is how to explain it to others
In very very very simple ways ..
is a P.H.D subject by itself
)
;with src
as
(
select *,
case
when checksent < ot2 then 0
else checksent - ot2
end as left_over
from @t
)
select *,
case
when t.ot1 < left_over then 0
else t.ot1 - left_over
end as left_over
from @t t
join src on t.id = src.id
the result is
id leftover1 leftover2
1 0 26
2 4 22
3 30 0
since 2nd account is priority it should be
1 26 20
2 22 0
3 0 0 --8 discarded
;with ct
as
(select id, ot1, ot2, checksent,deducted2 =
case
when checksent < ot2 then checksent
else ot2
end
, remaining2 = checksent - case
when checksent < ot2 then checksent
else ot2
end
from @t
)
select id, ot1, ot2
, deducted1 = case when remaining2 > 0 and remaining2 <= ot1 then remaining2 else case when remaining2=0 then 0 else ot1 end end
, deducted2
from ct
i tried doing this !!
i think mine is shorter .. anyhow please take a look
case
when value1-checkamt > 0 then value1 else value1-checkamt end
as value1_checkamt
when value1-checkamt > 0 and value2 - ( value1-checkamt ) <= 0
then value2 - ( value1-checkamt )
else value2 end
as value2_checkamt
end
your query
declare @t table (id int primary key, value1 int, value2 int, checkamt int)
insert @t (id,value1,value2,checkamt) values(1,26,36,16) --0,16
insert @t (id,value1,value2,checkamt) values(2,26,36,40) --4,36
insert @t (id,value1,value2,checkamt) values(3,22,0,30) --22,0
select id,
case
when value1-checkamt > 0 then value1 else value1-checkamt end
as value1_checkamt,
case when value1-checkamt > 0 and value2 - ( value1-checkamt ) <= 0
then value2 - ( value1-checkamt )
else value2 end
as value2_checkamt
from @t
not giving correct result
correct result is
id, value1_check_amt, value2_check_amt
1,0,16
2,4,36
3,22,0
please note that value2 is priority, we will first adjust from value2 and then value1
ok .. please see this .. this is more programming to the data and then any general SQL ..please note
select
case when value2 > checkamt then 0 when value2 < checkamt and value2 <> 0 then checkamt - value2 when value2 =0 then value1 end as value1
,
case when value2 > checkamt then checkamt when value2 < checkamt then value2 when value2 =0 then 0 end as value2
from @t