sql—如何将特定行转换为列

sh7euo9m  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(248)

我每月都会根据国家和产品统计账目。最后我得到一张表格,上面显示了每个月的情况、国家和产品,以及当月的数量。我希望能够从该表中提取每个产品和国家,然后为每个月创建一列计数。

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

我试过使用case,但对于plcmnt\mnth,我试过使用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 |
+--------------+---------+---------------+------+--------+
zrfyljdw

zrfyljdw1#

下面是如何实现 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;

相关问题