首页 > 解决方案 > 如何将特定行转置为列

问题描述

我根据国家和产品统计每个月的账户。我最终得到一个表格,显示每个月、国家和产品,以及该月的计数。我希望能够从该表中提取每个产品和国家/地区,然后每个月都有一个带有计数的列。


+---------------+--------------+---------+-----------------+
|  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 |
+--------------+---------+---------------+------+--------+

标签: sqlhive

解决方案


以下是您将如何实现这些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;

推荐阅读