两个查询及其和的差

时间:2018-08-07 20:34:13

标签: sql join union difference

下面是两个我想加入的简单/相似查询。我还希望有一列包含两个查询中两个和之间的差。

(我在两个查询的连接方面找到了帮助,但我认为有一个更简单的解决方案,并且对SQL还是陌生的)

我希望输出为4列:

  1. 邮寄日期
  2. 所有付款
  3. CCP_Payments
  4. 所有付款-CCP付款(减去​​两个)

查询1:

SELECT
TDL.POST_DATE
, SUM(CASE WHEN TDL.DETAIL_TYPE IN(2,5,11,20,22,32,33) THEN TDL.AMOUNT*-1 ELSE 0 END) PAYMENTS

FROM
STG_OJDT.STG_CL.CLARITY_TDL_TRAN TDL

WHERE
TDL.POST_DATE = '2018-08-01 00:00:00'
AND TDL.SERV_AREA_ID = 10

GROUP BY 
TDL.POST_DATE

Query2:

SELECT
TDL.POST_DATE
, SUM(CASE WHEN TDL.DETAIL_TYPE IN(2,5,11,20,22,32,33) THEN TDL.AMOUNT*-1 ELSE 0 END) CCP_PAYMENTS

FROM
STG_OJDT.STG_CL.CLARITY_TDL_TRAN TDL

WHERE
TDL.POST_DATE = '2018-08-01 00:00:00'
AND TDL.SERV_AREA_ID = 10
AND TDL.BILL_AREA_ID IN (810000020, 810000025, 810000030)
GROUP BY 
TDL.POST_DATE

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合在一行中计算两个值:

SELECT TDL.POST_DATE,
       SUM(CASE WHEN TDL.DETAIL_TYPE IN (2, 5, 11, 20, 22, 32, 33) THEN TDL.AMOUNT*-1 ELSE 0 END) as PAYMENTS,
       SUM(CASE WHEN TDL.DETAIL_TYPE IN (2, 5, 11, 20, 22, 32, 33) AND TDL.BILL_AREA_ID IN (810000020, 810000025, 810000030) THEN TDL.AMOUNT*-1 ELSE 0 END) as CCP_PAYMENTS
FROM STG_OJDT.STG_CL.CLARITY_TDL_TRAN TDL
WHERE TDL.POST_DATE = '2018-08-01 00:00:00' AND
      TDL.SERV_AREA_ID = 10    
GROUP BY  TDL.POST_DATE;

但是,如果您只想有所不同:

SELECT TDL.POST_DATE,
       SUM(CASE WHEN TDL.DETAIL_TYPE IN (2, 5, 11, 20, 22, 32, 33) THEN TDL.AMOUNT*-1 ELSE 0 END) as diff
FROM STG_OJDT.STG_CL.CLARITY_TDL_TRAN TDL
WHERE TDL.POST_DATE = '2018-08-01 00:00:00' AND
      TDL.SERV_AREA_ID = 10 AND 
      TDL.BILL_AREA_ID NOT IN (810000020, 810000025, 810000030) 
GROUP BY TDL.POST_DATE