SQL 查询总计

SQL Query to find Total

我的 table 结构如下:

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

并且我想获取每只股票的实际收盘数量记录。

SELECT STOCKNO,
       SUM(case when OP = '-' then -QTY else QTY end) as BALANCE
FROM DT 
GROUP BY STOCKNO

在总和中使用一个案例

select STOCKNO, sum(case when OP = '+' then 1 else -1 end * QTY) as StockLevel
from DT
group by STOCKNO

另一个选项(只是为了好玩)是 concat() OP 和 Qty

例子

Select STOCKNO
      ,Ttl = sum(convert(decimal(10,2),concat(OP,QTY)))
 from YourTable
 Group By STOCKNO

Returns

STOCKNO Ttl
12345   -15.00
123456  9.00
select STOCKNO,OP, sum(QTY) OVER(PARTITION BY STOCKNO,OP) as StockLevel
from DT