我是一个完整的 SQL 新手,并且有两个查询到我想要的结果,但我认为我没有UNION
正确使用它们来组合它们。我之前在这个网站上得到了一些帮助,其中有一部分是查询。下面是我所拥有的缩短版本。
WITH RemoveData
AS (SELECT a.PLANT_NO,
a.ALLOC_WHDV_VOL,
a.KW_CTR_REDELIVERED_HV,
a.MTR_NO,
a.MTR_SFX,
a.TRNX_ID,
a.REC_STATUS_CD,
MAX(a.ACCT_DT) ACCT_DT
FROM GasStmt a
INNER JOIN SettleSum c
ON a .= c.TRNX_ID
AND a.MTR_NO
||a.MTR_SFX = c.MTR_NO
||c.MTR_SFX
LEFT OUTER JOIN FuelsCat d
ON a.TRNX_ID = d.TRNX_ID
AND a.MTR_NO
||a.MTR_SFX = d.MTR_NO
||d.MTR_SFX
WHERE a.REC_STATUS_CD = 'RR'
GROUP BY a.PLANT_NO,
a.ALLOC_WHDV_VOL,
a.KW_CTR_REDELIVERED_HV,
a.MTR_NO,
a.MTR_SFX,
a.TRNX_ID,
a.REC_STATUS_CD
HAVING COUNT(a.REC_STATUS_CD) > 2)
SELECT plant_no "PlantNumber",
SUM(-a.ALLOC_WHDV_VOL) "PlantStandardGrossWellheadMcf",
SUM(KW_CTR_REDELIVERED_HV) "KeepWholeResidueMMBtu"
FROM RemoveData a
GROUP BY plant_no
UNION
SELECT a.PLANT_NO "PlantNumber",
SUM(a.ALLOC_WHDV_VOL) "PlantStandardGrossWellheadMcf",
SUM(CASE
WHEN a.REC_STATUS_CD = 'RR' THEN -a.KW_CTR_REDELIVERED_HV
ELSE a.KW_CTR_REDELIVERED_HV
END) "KeepWholeResidueMMBtu"
FROM GasStmt a
INNER JOIN SettleSum c
ON a.TRNX_ID = c.TRNX_ID
AND a.MTR_NO
||a.MTR_SFX = c.MTR_NO
||c.MTR_SFX
LEFT OUTER JOIN FuelsCat d
ON a.TRNX_ID = d.TRNX_ID
AND a.MTR_NO
||a.MTR_SFX = d.MTR_NO
||d.MTR_SFX
LEFT OUTER JOIN (SELECT MTR_NO,
MTR_SFX,
TRNX_ID,
REC_STATUS_CD,
MAX(ACCT_DT) ACCT_DT
FROM GasStmt
WHERE REC_STATUS_CD = 'RR'
GROUP BY MTR_NO,
MTR_SFX,
TRNX_ID,
REC_STATUS_CD
HAVING COUNT(TRNX_ID) > 1) b
ON a.MTR_NO = b.MTR_NO
AND a.TRNX_ID = b.TRNX_ID
AND a.Rec_Status_Cd = b.REC_STATUS_CD
AND a.Acct_Dt = b.ACCT_DT
WHERE TO_CHAR(a.PROD_DT, 'YYYY') >= TO_CHAR(ADD_MONTHS(SYSDATE, -36), 'YYYY')
AND a.STATUS_UNIT_TM_CD = 'M'
AND b.MTR_NO IS NULL
GROUP BY a.PLANT_NO
上面的查询返回:
PlantNumber | PlantStandardGrossWellheadMcf |KeepWholeResidueMMBtu
2 | 0 | -3.96
2 | 80 | 100
43 | 150 | 0
133 | 75 | 0
如果我自己使用 CTE 运行第一个查询,这就是我得到的:
PlantNumber | PlantStandardGrossWellheadMcf |KeepWholeResidueMMBtu
2 | 0 |-3.96
单独运行第二个查询,这是我得到的示例数据示例:
PlantNumber | PlantStandardGrossWellheadMcf |KeepWholeResidueMMBtu
2 | 80 | 100
43 | 150 | 0
133 | 75 | 0
我的预期结果是根据植物编号组合数据。可以用 UNION 完成还是我做错了什么?这是我希望实现的目标:
PlantNumber | PlantStandardGrossWellheadMcf |KeepWholeResidueMMBtu
2 | 80 | 96.04
43 | 150 | 0
133 | 75 | 0