【发布时间】: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