【问题标题】:Combining two select statement into single output将两个选择语句组合成单个输出
【发布时间】:2018-04-18 13:51:24
【问题描述】:

我正在尝试构建一个查询,将两个 SELECT 语句连接到一个输出中。

我正在使用 Amazon Redshift。

我已附上我建立的查询如下:

with q1 as (
    select count(invoices) as count,to_char(billtime,'yyyy-mm-dd'), store 
    from sales
    group by to_char(billtime,'yyyy-mm-dd'), store
),
q2 as (
    select count(a.invoices) as count1, b.store,
        to_char(a.billtime,'yyyy-mm-dd')
    from sales_detail a, dim_store b
    where a.store_id = b.id
    group by b.store, to_char(a.billtime,'yyyy-mm-dd')
)
select q1.count(invoices), q2.count(a.invoices), q1.store
from q1
left join q2
    on q1.store = q2.store
group by q1.store; 

我收到一条错误消息,提示无效操作列不存在未命名连接。

谁能帮忙。谢谢..

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

    您的选择语句似乎是问题所在。由于您已经为两个 CTE 中的每个计数设置了别名,您可以只选择这些别名:

    SELECT
        q1.store, q1.count, q2.count1
    FROM q1
    LEFT join q2
        ON q1.store = q2.store
    GROUP BY q1.store;
    

    就进一步的改进而言,由于您最终希望从两个表中进行商店级别的聚合,因此无需在每个 CTE 中按帐单日期商店进行聚合。所以,对于第一个 CTE,你可以使用这个:

    WITH q1 AS (
        SELECT store, COUNT(invoices) AS count
        FROM sales
        GROUP BY store
    )
    

    但也许您从其他需要双重聚合的地方提取 CTE。

    【讨论】:

    • 感谢您的帮助,得到了预期的结果。
    【解决方案2】:

    您可以使用 UNION 代替 CTE,并注意两个查询具有相同的列名。之后转置列和行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多