我的SQL组语句结果如下表所示。从这个表中,当价格和日期匹配时,我需要从Qty中用Code ='S'减去Qty,代码='B'。
例如,在下表中,我需要将值存储在工作变量中。
1)前2行的100-50 = 50 2)第3行和第4行60 -30 = 30 3)最后一行,因为它没有代码'S',它应该只返回20
表
Price Date Code Sum(Qty)
9.0 201512 B 100
9.0 201512 S 50
8.0 201506 B 60
6.0 201506 S 30
5.0 201508 B 20
用于获取上表的SQL查询
select Price, Date, Code,sum(Qty) from Table
where Type = 'A' and Acct = 'CLOSED'
group by Price,Date,Code
order by Price,Date
我是否可以使用CASE语句修改上面键入的现有SQL语句以获取所需的输出。我尝试过但是Cursor一个接一个地返回,CASE似乎不起作用
exec sql
declare c1 cursor for
select Price, Date, Code,
Case when Code ='B' then ifnull(sum(Qty),0)
when Code ='S' then (-1 * ifnull(sum(Qty),0)) end
from Table
where Type = 'A' and Acct = 'CLOSED'
group by Price,Date,Code
order by Price,Date
exec sql
open c1
exec sql
fetch c1 into :var_price, :var_date, :var_code, :var_Bqty, :VarSqty
在iseries系统上使用SQLRPGLE。
答案 0 :(得分:4)
您可以使用条件聚合:
select Price, Date,
sum(case when code = 'B' then Qty when code = 'S' then -QTY end) as diff
from Table
where Type = 'A' and Acct = 'CLOSED'
group by Price, Date
order by Price, Date;