我正在触发以下查询>>
SELECT sauda_date,
Sum(CASE
WHEN buy_sell = 1
AND scrip_code = 'ADANIENT'
AND sauda_date BETWEEN CONVERT(DATETIME, '1 Mar 2013') AND
CONVERT(DATETIME, '1 Apr 2013') THEN
trade_qty
ELSE 0
END) AS BuyQty,
Sum(CASE
WHEN buy_sell = 2
AND scrip_code = 'ADANIENT'
AND sauda_date BETWEEN CONVERT(DATETIME, '1 Mar 2013') AND
CONVERT(DATETIME, '1 Apr 2013') THEN
trade_qty
ELSE 0
END) AS SellQty,
Sum(CASE
WHEN buy_sell = 1
AND scrip_code = 'ADANIENT' THEN trade_qty
ELSE 0
END) - Sum(CASE
WHEN buy_sell = 2
AND scrip_code = 'ADANIENT' THEN trade_qty
ELSE 0
END) AS CarryForword
FROM tradefile
WHERE scrip_code = 'ADANIENT'
GROUP BY sauda_date
我得到以下结果:
sauda_date | Buy_Qty | SellQty | CarryForward
01 Mar 2013 2000 0 2000
01 Mar 2013 0 2000 0
01 Mar 2013 4000 0 4000
02 Mar 2013 0 1000 3000
02 Mar 2013 2000 0 5000
03 Mar 2013 0 4000 1000
但我希望它是:
sauda_date | Buy_Qty | SellQty | CarryForward
01 Mar 2013 6000 2000 4000
02 Mar 2013 2000 1000 5000
03 Mar 2013 0 4000 1000
从表格中我们可以看出:
CaryyForward=Buy_Qty-Sell_Qty;
01 Mar 2013 is date and Buy_Qty=sum(buy_Qty) for 01 Mar 2013.
02 Mar 2013 is date and Buy_Qty=sum(buy_Qty) for 02 Mar 2013.
[Sell_Qty 和 CarryForward 相同]。
我尝试了不同的 group by in case when ,但后来知道它在 case when 中是不允许的。
我也尝试使用不同的 where 条件但没有奏效。
请帮我。