我的表结构如下:
STOCKNO QTY OP
12345 1.00 +
12345 25.00 -
12345 1.00 -
12345 10.00 +
123456 10.00 +
123456 1.00 -
我想通过+, -
得到每个stockno的实际数量余额+ (i.e. Purchase Qty)
- (i.e. Sales Qty)
但是对于上面我得到的总购买数量&使用以下查询销售数量:
SELECT STOCKNO, SUM(QTY) as QTY, OP
FROM DT
GROUP BY STOCKNO, OP
我希望获得每只股票的实际收盘数量。
答案 0 :(得分:2)
SELECT STOCKNO,
SUM(case when OP = '-' then -QTY else QTY end) as BALANCE
FROM DT
GROUP BY STOCKNO
答案 1 :(得分:0)
在总和
中使用案例select STOCKNO, sum(case when OP = '+' then 1 else -1 end * QTY) as StockLevel
from DT
group by STOCKNO
答案 2 :(得分:0)
另一个选项(只是为了好玩)是concat()OP和Qty
示例强>
Select STOCKNO
,Ttl = sum(convert(decimal(10,2),concat(OP,QTY)))
from YourTable
Group By STOCKNO
<强>返回强>
STOCKNO Ttl
12345 -15.00
123456 9.00
答案 3 :(得分:0)
select STOCKNO,OP, sum(QTY) OVER(PARTITION BY STOCKNO,OP) as StockLevel
from DT