第一次查询:
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
这可能吗?
答案 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;
答案 1 :(得分:5)
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
。