请教一个SQL view问题
有这么一个表:
ProductID, QTY, TYPE
1 10 出库
1 5 入库
2 20 出库
3 15 入库
我想把他们作成一个view的效果
ProductID 出库数 入库数 剩余
1 10 5 -5
2 20 0 -20
3 0 15 15
请教sql语句该怎么写
------解决方案--------------------create table t(ProductID int,QTY int,TYPE varchar(10))
insert t select 1,10, '出库 '
union all select 1,5, '入库 '
union all select 2,20, '出库 '
union all select 3,15, '入库 '
select ProductID,
出库数=sum(case when TYPE= '出库 ' then QTY else 0 end),
入库数=sum(case when TYPE= '入库 ' then QTY else 0 end),
剩余=sum(case when TYPE= '入库 ' then QTY else -QTY end)
from t
group by ProductID
ProductID 出库数 入库数 剩余
----------- ----------- ----------- -----------
1 10 5 -5
2 20 0 -20
3 0 15 15
------解决方案----------------------用case when 处理
select
ProductID,
sum(case when TYPE= '出库 ' then QTY else 0 end) as 出库数,
sum(case when TYPE= '入库 ' then QTY else 0 end) as 入库数,
sum(case when TYPE= '入库 ' then QTY else -QTY end) as 剩余
from 表名
group by ProductID
order by ProductID
------解决方案--------------------SELECT ProductID,
SUM(CASE WHEN TYPE = '出库 ' THEN QTY ELSE 0 END) 出库数,
SUM(CASE WHEN TYPE = '入库 ' THEN QTY ELSE 0 END) 入库数,
SUM(CASE WHEN TYPE = '出库 ' THEN QTY ELSE -QTY END) 剩余
FROM tblTest
GROUP BY ProductID
ORDER BY ProductID
------解决方案--------------------SELECT ProductID,
SUM(CASE WHEN TYPE = '出库 ' THEN QTY ELSE 0 END) 出库数,
SUM(CASE WHEN TYPE = '入库 ' THEN QTY ELSE 0 END) 入库数,
SUM(CASE WHEN TYPE = '剩余 ' THEN QTY ELSE -QTY END) 剩余
FROM tblTest
GROUP BY ProductID
ORDER BY ProductID
------解决方案--------------------SELECT ProductID,
SUM(CASE WHEN TYPE = '出库 ' THEN QTY ELSE 0 END) 出库数,
SUM(CASE WHEN TYPE = '入库 ' THEN QTY ELSE 0 END) 入库数,
SUM(CASE WHEN TYPE = '入库 ' THEN QTY ELSE -QTY END) 剩余
FROM tblTest
GROUP BY ProductID
ORDER BY ProductID
---------------------------------
看错了,不好意思: 剩余 = 入库 - 出库