Need To select Data From One Table After Minus With One Value
这是我已经问过的问题,这个解决方案将一个值输入到表和结果中。但我需要更多的输入值为不同的类别和每个类别的输出,例如(基于上一个问题)
Table 1
SNo Amount categories
1 100 type1
2 500 type1
3 400 type1
4 100 type1
5 100 type2
6 200 type2
7 300 type2
8 500 type3
9 100 type3
和
values for type1 - 800
values for type2 - 200
values for type3 - 100
输出需求是
for type-1
800 - 100 (Record1) = 700
700 - 500 (record2) = 200
200 - 400 (record3) = -200
表记录从记录3开始,余额值为Balance 200
Table-Output
SNo Amount
1 200
2 100
这意味着如果第一个表中的负800,前2个记录将被删除,而第三个记录200为平衡
对于剩余类型也有相同的操作,该怎么做?
发布于 2013-07-25 10:18:09
with T1 as
(
select t.*,
SUM(Amount) OVER (PARTITION BY [Type] ORDER BY [SNo])
-
CASE WHEN Type='Type1' then 800
WHEN Type='Type2' then 200
WHEN Type='Type3' then 100
END as Total
from t
)select Sno,Type,
CASE WHEN Amount>Total then Total
Else Amount
end as Amount
from T1 where Total>0
order by Sno
更新:如果类型不是固定的,那么您应该为它们创建一个表,例如:
CREATE TABLE types
([Type] varchar(5), [Value] int);
insert into types
values
('type1',800),
('type2',200),
('type3',100);
并使用以下查询:
with T1 as
(
select t.*,
SUM(Amount) OVER (PARTITION BY t.[Type] ORDER BY [SNo])
-
ISNULL(types.Value,0) as Total
from t
left join types on (t.type=types.type)
)select Sno,Type,
CASE WHEN Amount>Total then Total
Else Amount
end as Amount
from T1 where Total>0
order by Sno
更新:对于MSSQL2005,只需用(select SUM(Amount) from t as t1 where t1.Type=t.Type and t1.SNo<=t.SNo)
替换SUM(Amount) OVER (PARTITION BY t.[Type] ORDER BY [SNo])
即可
with T1 as
(
select t.*,
(select SUM(Amount) from t as t1
where t1.Type=t.Type
and t1.SNo<=t.SNo)
-
ISNULL(types.Value,0) as Total
from t
left join types on (t.type=types.type)
)select Sno,Type,
CASE WHEN Amount>Total then Total
Else Amount
end as Amount
from T1 where Total>0
order by Sno
https://stackoverflow.com/questions/17853211
复制相似问题