2013-07-25 45 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