sql - 如何将特定行转置为列
问题描述
我根据国家和产品统计每个月的账户。我最终得到一个表格,显示每个月、国家和产品,以及该月的计数。我希望能够从该表中提取每个产品和国家/地区,然后每个月都有一个带有计数的列。
+---------------+--------------+---------+-----------------+
| plcmnt_mnth | product_code | ctry_cd | accounts_placed |
+---------------+--------------+---------+-----------------+
| August | Lending | AR | 751 |
| August | Charge | MX | 2137 |
| August | Charge | AR | 240 |
| August | Lending | MX | 3307 |
| July | Charge | AR | 67 |
| July | Lending | AR | 122 |
| July | Charge | MX | 977 |
| July | Lending | MX | 694 |
| Pre-June 2019 | Charge | AR | 16 |
| Pre-June 2019 | Lending | AR | 25 |
| Pre-June 2019 | Charge | MX | 76 |
| Pre-June 2019 | Lending | MX | 72 |
+---------------+--------------+---------+-----------------+
我曾尝试对 plcmnt_mnth 使用 CASE WHEN,我曾尝试使用 coalesce 但似乎无法正确使用。我还尝试在这里查看有关转置的其他问题,但似乎找不到适合我正在尝试做的事情的问题。
这是我用来提取数据的代码。它是从一个包含所有帐户列表的表中提取的。
select plcmnt_mnth, product_code, ctry_cd, count(acct) as accounts_placed
from cj_test_placements
group by plcmnt_mnth, product_code, ctry_cd;
我希望每个月都有一个新专栏。从中提取的表格设置为将 2019 年 6 月之前的任何日期标记为 2019 年 6 月之前的日期,之后的每个月都按月计算。我希望能够做到这一点,以便一旦我们到了 10 月并且有 10 月的计数,它会添加另一列,然后是 11 月等。
+--------------+---------+---------------+------+--------+
| product_code | ctry_cd | Pre-June 2019 | July | August |
+--------------+---------+---------------+------+--------+
| Charge | AR | 16 | 67 | 240 |
| Lending | AR | 25 | 122 | 751 |
| Charge | MX | 76 | 977 | 2137 |
| Lending | MX | 72 | 694 | 3307 |
+--------------+---------+---------------+------+--------+
解决方案
以下是您将如何实现这些case
语句
select
product_code,
ctry_code,
max(case when accounts_placement_mnth='Pre-June 2019' then accounts_placed end) as Pre-June-2019,
max(case when accounts_placement_mnth='July' then accounts_placed end) as July,
max(case when accounts_placement_mnth='August' then accounts_placed end) as August
from cj_test_placements
group by product_code, ctry_code;
推荐阅读
- reactjs - react-router 如何在页面刷新时保持位置状态?
- caffe - Caffe: Check failed: error == cudaSuccess (48 vs. 0) no kernel image is available for execution on the device error on Jetson TX1
- git - git reset --soft 用大文件挽回面子
- asynchronous - 重建读取端 DB 时事件乱序
- android - 错误:包 android.v7.app 不存在
- ms-access - 如何根据 MS Access 中的记录输出多个 PDF 文件?
- c++ - 如果我只有 1 个读线程和 1 个写线程, queue.empty() 和 queue.full() 会保证线程安全吗?
- ios - 如何防止 UISearchController 显示导航栏?
- javascript - 如何按数值对 json 进行排序?
- docker - 从“docker ps”获取容器ID的Shell命令