合并2个聚合查询:以单行显示结果(DB2)

时间:2015-12-18 16:19:13

标签: db2

第一次查询

SELECT count(*) AS TAXTOTAL
FROM T_tx_tax_report rpt
  INNER JOIN T_TX_TAX_REPORT_TRANSACTION trans
    ON rpt.TAX_REPORT_ID = trans.TAX_REPORT_ID
WHERE rpt.created_ts < '10/01/2015'
      AND trans.TAX_REPORT_SOURCE NOT IN ('MIGR')
GROUP BY (rpt.created_ts), trans.TAX_REPORT_SOURCE, rpt.TOTAL_WAGES
ORDER BY (rpt.created_ts) DESC, trans.TAX_REPORT_SOURCE ASC

第二次查询

SELECT count(*) AS TAXTOTAL
FROM T_tx_tax_report rpt
  INNER JOIN T_TX_TAX_REPORT_TRANSACTION trans
    ON rpt.TAX_REPORT_ID = trans.TAX_REPORT_ID
WHERE rpt.created_ts = '10/01/2015'
      AND trans.TAX_REPORT_SOURCE NOT IN ('MIGR')
GROUP BY (rpt.created_ts), trans.TAX_REPORT_SOURCE, rpt.TOTAL_WAGES
ORDER BY (rpt.created_ts) DESC, trans.TAX_REPORT_SOURCE ASC

WHERE子句中的created_ts条件是2个查询之间的唯一区别。组合查询以在一行中显示结果。感谢。

            No. Prior to             No. On
             10/01/2015               10/1/2015           Total No.      
 a                     5                    1                   6
 b                     10                   3                   13

1 个答案:

答案 0 :(得分:0)

你只需要简单地将一个或另一个条件为真的事件加起来,就像这些一样:

SELECT 
  ...,
  sum(case when rpt.created_ts < '10/01/2015' then 1 end) "No. Prior to date",
  sum(case when rpt.created_ts = '10/01/2015' then 1 end) "No. On date",
  count(*) as "Total No."
FROM    T_tx_tax_report rpt
INNER JOIN T_TX_TAX_REPORT_TRANSACTION trans 
ON rpt.TAX_REPORT_ID =      trans.TAX_REPORT_ID
where   rpt.created_ts <= '10/01/2015'
...