我每个月都会根据国家和地区来计算帐户数。我最后得到一个表格,该表格显示每个月,国家和产品以及该月的计数。我希望能够从该表中提取每个产品和国家/地区,然后每个月都有一个带有计数的列。
+---------------+--------------+---------+-----------------+
| 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 WHEN作为plcmnt_mnth,我尝试使用合并,但似乎无法正确处理。我还尝试过查看有关移调的其他问题,但似乎找不到适合我尝试做的问题。
这是我用来提取数据的代码。它是从包含所有帐户列表的表中提取的。
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月之前的日期,之后每个月都会进行计数。我希望能够做到这一点,以便一旦我们到达十月,并且有一个十月的计数,它将添加另一列,然后是十一月,等等。
+--------------+---------+---------------+------+--------+
| 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 |
+--------------+---------+---------------+------+--------+
答案 0 :(得分:2)
这是实现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;