select a.LOB, SUM(a.GPW) AS XGPW,SUM(b.GPW) AS YGPW,SUM(a.GPW) - SUM(b.GPW) AS GPW_DIFF
FROM SDSS.DSS_SALES_PRODUCTION_DTLS a,
SDSS.DSS_SALES_PRODUCTION_DTLS b
where a.LOB = b.LOB and
a.account_year=2014 and b.account_year=2015
GROUP BY a.LOB
我想打印2014年和2015年产生的总GPW。在Db中,我每个月都有单独的GPW值等,我想将它们全部加起来。对于2014年,总和是正确的但不是2015年。建议
答案 0 :(得分:2)
不要两次加入同一个表,而是最好使用CASEes:
SELECT LOB, XGPW, YGPW, XGPW - YGPW AS GPW_DIFF
from
(
select LOB,
SUM(CASE WHEN account_year=2014 THEN a.GPW ELSE 0 END) AS XGPW,
SUM(CASE WHEN account_year=2015 THEN a.GPW ELSE 0 END) AS YGPW,
FROM SDSS.DSS_SALES_PRODUCTION_DTLS
where account_year in (2014, 2015)
GROUP BY LOB
) dt
答案 1 :(得分:1)
您需要像这样更改and
条件:
a.account_year in(2014,2015)
<击> 所以它就像
select a.LOB, SUM(a.GPW) AS XGPW,SUM(b.GPW) AS YGPW,SUM(a.GPW) - SUM(b.GPW) AS GPW_DIFF
FROM SDSS.DSS_SALES_PRODUCTION_DTLS a,
SDSS.DSS_SALES_PRODUCTION_DTLS b
where a.LOB = b.LOB and
a.account_year in(2014,2015)
GROUP BY a.LOB
击> <击> 撞击> 修改强>
SELECT LOB, XGPW, YGPW, (XGPW - YGPW) AS GPW_DIFF
from
(
select LOB,
SUM(CASE WHEN account_year=2014 THEN GPW ELSE 0 END) AS XGPW,
SUM(CASE WHEN account_year=2015 THEN GPW ELSE 0 END) AS YGPW,
FROM SDSS.DSS_SALES_PRODUCTION_DTLS
where account_year in (2014, 2015)
GROUP BY LOB
) x
答案 2 :(得分:1)
&#34; OR&#34;需要而不是&#34; AND&#34;。
select a.LOB, SUM(a.GPW) AS XGPW,SUM(b.GPW) AS YGPW,SUM(a.GPW) - SUM(b.GPW) AS GPW_DIFF
FROM SDSS.DSS_SALES_PRODUCTION_DTLS a,
SDSS.DSS_SALES_PRODUCTION_DTLS b
where a.LOB = b.LOB and
(a.account_year=2014 or b.account_year=2015)
GROUP BY a.LOB