【问题标题】:merge two COUNT in one SQL query在一个 SQL 查询中合并两个 COUNT
【发布时间】:2020-08-28 23:25:41
【问题描述】:

我需要进行查询以显示 new_customers X customers_cancellations

通过这个查询,我可以按月获取 new_customers:

选择 count(start_date), to_char(start_date, 'MM') 作为 monthNumber, to_char(start_date, 'YY') 作为 yearNumber 来自 start_date 不为空的客户 按 to_char(start_date, 'MM'), to_char(start_date, 'YY') 分组 按年号、月号排序;

有了这个,我可以按月让客户取消:

select count(cancellation_date), to_char(cancellation_date, 'MM') as monthNumber, to_char(cancellation_date, 'YY') as yearNumber 来自取消日期不为空的客户 按 to_char(cancellation_date, 'MM')、to_char(cancellation_date, 'YY') 分组 按年号、月号排序;

这两个查询都返回如下内容:

计数|月数|年数 1 | 1 | 20 7 | 2 | 20 5 | 3 | 20

但我想要这样的东西:

customer_out_count|customer_in_count|月数|年数 0 |1 | 1 | 20 0 |7 | 2 | 20 1 |0 | 3 | 20 0 |1 | 4 | 20 5 |7 | 5 | 20 1 |5 | 6 | 20

我已经尝试过这个其他查询:

选择'start'作为类型,count(start_date)作为计数,to_char(start_date,'MM')作为monthNumber,to_char(start_date,'YY')作为yearNumber 来自 start_date 不为空的客户 按 to_char(start_date, 'MM'), to_char(start_date, 'YY') 分组 联盟 选择'cancellation'作为类型,count(cancellation_date)作为counta,to_char(cancellation_date,'MM')作为monthNumber,to_char(cancellation_date,'YY')作为yearNumber 来自取消日期不为空的客户 按 to_char(cancellation_date, 'MM')、to_char(cancellation_date, 'YY') 分组 按年号、月号排序;

结果“ok”:

类型 |新计数 |月数|年数 开始 |1 | 1 | 20 取消 |1 | 1 | 20 取消 |7 | 2 | 20 开始 |3 | 3 | 20 取消 |1 | 4 | 20 开始 |7 | 5 | 20 开始 |5 | 6 | 20

但是我需要对代码做一些操作来实现我需要的。

如何将这两个查询合并为一个?我正在使用 postgreslq。

【问题讨论】:

  • mysql 还是 postgres?请仅标记一个数据库。
  • @GMB 抱歉,我正在使用 postgres

标签: sql postgresql datetime sum unpivot


【解决方案1】:

一个选项取消透视行,然后聚合。在 Postgres 中,您可以使用横向连接来表达这一点:

select
    sum(x.customer_in_count)  as customer_in_count,
    sum(x.customer_out_count) as customer_out_count
    to_char(x.dt, 'MM') as monthNumber, 
    to_char(x.dt, 'YY') as yearNumber
from customer c
cross join lateral (values
    (c.start_date, 1, 0), (c.cancellation_date, 0, 1)
) as x(dt, customer_in_count, customer_out_count)
where x.dt is not null
group by monthNumber, yearNumber
order by monthNumber, yearNumber

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2016-01-23
    相关资源
    最近更新 更多