PostgreSQL在每个查询中合并两个查询,其中COUNT和GROUP BY

时间:2014-04-02 15:32:39

标签: postgresql join group-by crosstab

第一次查询:

SELECT date_trunc('day', date1) as date, COUNT(*) AS count_a 
FROM table_a GROUP BY date

结果:

date                    count_a
2014-04-01 00:00:00.0   1011642
2014-04-02 00:00:00.0   309048

第二次查询:

SELECT date_trunc('day', date1) as date, COUNT(*) AS count_b 
FROM table_b GROUP BY date

结果:

date                    count_b
2014-04-01 00:00:00.0   2342
2014-04-02 00:00:00.0   43432

我想得到:

date                    count_a  count_b
2014-04-01 00:00:00.0   1011642  2342
2014-04-02 00:00:00.0   309048   43432

这可能吗?

2 个答案:

答案 0 :(得分:5)

简单的UNION ALL应该可以实现。

SELECT date1 date, SUM(a) count_a, SUM(b) count_b 
FROM (
  SELECT DATE_TRUNC('day', date1) date1, 1 a, 0 b FROM table_a 
  UNION ALL 
  SELECT DATE_TRUNC('day', date1) date1, 0 a, 1 b FROM table_b
) z 
GROUP BY date;

编辑:Here's an SQLfiddle

答案 1 :(得分:5)

使用FULL [OUTER] JOIN

SELECT *
FROM  (
   SELECT date1::date AS day, COUNT(*) AS count_a
   FROM   table_a
   GROUP  BY 1
   ) a
FULL JOIN (
   SELECT date1::date AS day, COUNT(*) AS count_b
   FROM   table_b
   GROUP  BY 1
   ) b USING (day);
  • USING子句自动折叠到结果中的一个day
  • 要将日期投放到date。更快,更简单。

SQLfiddle(基于约阿希姆)。

次要差异:此查询返回NULL天数,一侧没有任何行。使用 COALESCE(count_b, 0) 来获取0