postgresql - PostgreSQL 中 CASE 表达式中的子查询
问题描述
我是新来的,在 PostgreSQL 中真的不那么出名。
我有两个表(每月汇总的表使用情况和显示历史所有客户 dunning_level 和 dunning_date 的表 customer_dunnings)。我需要向客户展示过去 3 个月内违反了使用情况的客户(我可以解决这个问题)。但我还需要显示客户是否有一个 dunning_level,如果是,他在那个月有哪个级别。
在表用法中,我有列 datetime,它的日期类似于“2019-09-01”,聚合后它总是显示每月的第一天。在 customer_dunnings 表上,我有一列 dunning_date,它的日期类似于“2019-09-15”,显示了客户达到催款级别的确切日期以及哪个 dunning_level。
我想显示dunning_level,以防客户在该usages.datetime 上有dunning_level。
我想用一个 CASE 表达式我可以做到这一点。
这是我的查询。希望你能帮助我。
SELECT
u.id,
u.datetime,
to_char(u.datetime, 'YYYYMM') "month",
u.customer_id,
u.customer_number CID,
case when u.customer_number in (select c.customer_number
from v_reporting_customer_dunnings d
left join v_reporting_cids c on c.customer_id=d.customer
left join usages u on u.customer_number=c.customer_number and to_char(u.datetime, 'YYYYMM')=to_char(d.dunning_date, 'YYYYMM')) then 'yes' else null end as dunning
FROM usages u
使用表的示例客户:
ID Datetime Month Customer_ID CID Dunning
11306415573 2019-09-01 201909 2039145295 80035006 yes
8208810439 2018-12-01 201812 2039145295 80035006 yes
7926569969 2018-11-01 201811 2039145295 80035006 yes
7654669868 2018-10-01 201810 2039145295 80035006 yes
表 v_reporting_customer_dunnings 上的示例客户:
Customer INVOICE DUNNING_LV INVOICE_DT DUNNING_DT
2039145295 90354914 LEVEL 10 2018-09-30 2018-11-16
2039145295 90226540 LEVEL 10 2018-04-30 2018-06-08
表 v_reporting_cids 上的示例客户:
Customer_ID Customer_Number
2039145295 80035006
2039145295 80035006
该客户的催款级别为 2 倍。1x 与表使用情况相同。在这种情况下,在我的查询中应该是一列,为我提供匹配年月的 dunning_level。
我期望/想要拥有的:
ID Datetime Month Customer_ID CID Dunning Dunning_Level
11306415573 2019-09-01 201909 2039145295 80035006 NULL NULL
8208810439 2018-12-01 201812 2039145295 80035006 NULL NULL
7926569969 2018-11-01 201811 2039145295 80035006 yes LEVEL 10
7654669868 2018-10-01 201810 2039145295 80035006 NULL NULL
解决方案
推荐阅读
- javascript - JS - 数字的幂符号/指数
- c - command terminated in attempt to assign a variable
- php - Faker imges not displaying properly
- mongodb - Mongodb - 每小时获取销售额
- c - 使用 execlp 在 C 中写入错误:Broken Pipe
- executable-jar - 无法使用从 MAVEN 创建的 JAR 直接运行 Jmeter 性能测试
- mysql - 将数据从 Maria DB 表导出到 CSV 文件的 AWS 权限问题
- ruby - 如何更改 rails_admin 中删除操作的自定义错误消息?
- python - 无法在 ROS 中检测到自定义消息子目录(即 package.msg)
- istio - 未使用 Istio 和 Sleuth 采样的跟踪