2013-07-25 21 views
1

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开始,余额值余额200

Table-Output 
SNo  Amount 
1   200 
2   100 

这意味着,如果减去第一表800第2条记录将被删除,并在第三个记录200天平

为还停留类型以及如何做同样的操作?

回答

0

SQLFiddle demo

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 demo

更新:对于MSSQL 2005只是(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 demo

+0

它不是固定为TYPE1,TYPE2像更换SUM(Amount) OVER (PARTITION BY t.[Type] ORDER BY [SNo]) ....这将是刚刚提到例如 – Suresh

+0

@Suresh我任何@valex在我的回答中添加了一个查询。 – valex

+0

它为什么显示错误? 'ORDER BY [SNo]' – Suresh