1

需要减去一个值后从一个表中选择数据

这是我已经问过的问题,也是表和结果的一个值输入的解决方案。但我需要更多不同类别的输入值和每个类别的输出,例如(基于上一个问题)

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 前两条记录将被删除,第三条记录中的 200 是余额

剩余类型的操作也相同,怎么做?

4

1 回答 1

0

SQLFiddle 演示

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

UPD:如果类型不固定,那么您应该为它们创建一个表,例如:

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

SQLFiddle 演示

更新:对于 MSSQL 2005,只需替换SUM(Amount) OVER (PARTITION BY t.[Type] ORDER BY [SNo])(select SUM(Amount) from t as t1 where t1.Type=t.Type and t1.SNo<=t.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

SQLFiddle 演示

于 2013-07-25T10:18:08.673 回答