简体   繁体   English

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

[英]SQL using the result of a UNION query in another query

How can I complete this query? 如何完成此查询?

Right now, the query I have working is this, but it is not producing the right data. 现在,我正在使用的查询就是这个,但它不能产生正确的数据。

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);

Instead of TABLE1, I need to feed the query with data from another query which looks like this: 代替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;

How do I do this? 我该怎么做呢?

Any part of a select query that receives a table (eg, a from clause, a join clause, etc) can receive a query surrounded in parenthesis - this is called a subquery. 接收表的select查询的任何部分(例如from子句, join子句等)都可以接收括号中的查询-这称为子查询。 Note that in Postgres this subquery must be given an alias (ie, a name that it can be referenced by). 请注意,在Postgres中, 必须给该子查询一个别名(即可以被其引用的名称)。 So in your case: 因此,在您的情况下:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM