SQL在另一个查询中使用UNION查询的结果

时间:2015-01-06 18:05:45

标签: sql postgresql select join

如何完成此查询?

现在,我工作的查询是这样的,但它没有产生正确的数据。

SELECT date, coalesce(count,0) AS count 
FROM 
    generate_series(
        '2014-12-13 12:00:00'::timestamp, 
        '2015-01-06 11:00:00'::timestamp, 
        '1 hour'::interval
    ) AS date 
    LEFT OUTER JOIN (
        SELECT 
            date_trunc('day', TABLE1.created_at) as day, 
            count(DISTINCT TABLE1.user) as count 
        FROM TABLE1 
        WHERE org_id = 1 
        GROUP BY day
    ) results ON (date = results.day);

而不是TABLE1,我需要使用另一个查询的数据来提供查询,如下所示:

SELECT TABLE2.user_a as userid, TABLE2.created_at as createdat from TABLE2 
UNION ALL 
SELECT TABLE3.user_b as userid, TABLE3.created_at as createdat from TABLE3 
UNION ALL 
SELECT TABLE4.sender as userid, TABLE4.created_at as createdat from TABLE4;

我该怎么做?

1 个答案:

答案 0 :(得分:1)

接收表(例如,select子句,from子句等)的join查询的任何部分都可以接收括号中包围的查询 - 这称为子查询。请注意,在Postgres中,此子查询必须被赋予别名(即,可以引用它的名称)。所以在你的情况下:

SELECT date, coalesce(count,0) AS count 
FROM 
    generate_series(
        '2014-12-13 12:00:00'::timestamp, 
        '2015-01-06 11:00:00'::timestamp, 
        '1 hour'::interval
    ) AS date 
    LEFT OUTER JOIN (
        SELECT 
            date_trunc('day', subquery.created_at) as day, 
            count(DISTINCT subquery.user) as count 
              -- Subquery here:
        FROM (SELECT TABLE2.user_a as userid, TABLE2.created_at as createdat from TABLE2 
              UNION ALL 
              SELECT TABLE3.user_b as userid, TABLE3.created_at as createdat from TABLE3 
              UNION ALL 
              SELECT TABLE4.sender as userid, TABLE4.created_at as createdat from TABLE4) 
             subquery 
        WHERE org_id = 1 
        GROUP BY day
    ) results ON (date = results.day);