sql - 带有 IN CLAUSE 动态值的 SQL Pivot
问题描述
我有以下格式的表格
细节
+-------------------+--------+------------+----------------+-------+
| LOB | Level | Year_Month | Classification | Count |
+-------------------+--------+------------+----------------+-------+
| Mergers& Acqu | Level3 | 2020-05 | Statement | 356 |
+-------------------+--------+------------+----------------+-------+
| Wealth Management | Level2 | 2020-05 | Lending | 23 |
+-------------------+--------+------------+----------------+-------+
| Finance | Level3 | 2020-06 | Statement | 65 |
+-------------------+--------+------------+----------------+-------+
如何旋转具有计数的 Year_month 列?
预期结果
+-------------------+--------+----------------+---------+---------+
| LOB | Level | Classification | 2020-05 | 2020-06 |
+-------------------+--------+----------------+---------+---------+
| Mergers& Acqu | Level3 | Statement | 356 | 0 |
+-------------------+--------+----------------+---------+---------+
| Wealth Management | Level2 | Lending | 23 | 0 |
+-------------------+--------+----------------+---------+---------+
| Finance | Level3 | Statement | 0 | 65 |
+-------------------+--------+----------------+---------+---------+
我尝试了以下查询,但没有得到想要的结果
SELECT * FROM DETAILS
PIVOT (SUM(Count) FOR YEAR_MONTH IN (SELECT distinct YEAR_MONTH FROM DETAILS))
如何使 IN CLAUSE 具有动态值而不是预设值?
解决方案
使用替换变量的选项:
SQL> set verify off
SQL> clear columns
columns cleared
SQL> column llist new_value slist
SQL> select listagg(ym, ', ') within group (order by ym) as llist
2 from (select distinct
3 chr(39) || year_month ||chr(39) || ' as "' || year_month ||'"' ym
4 from details
5 );
LLIST
--------------------------------------------------------------------------------
'2020-05' as "2020-05", '2020-06' as "2020-06"
SQL> select * from
2 (select lob, clevel, classification, year_month, ccount from details)
3 pivot (sum(ccount)
4 for year_month in (&slist));
LOB CLEVEL CLASSIFIC 2020-05 2020-06
----------------- ------ --------- ---------- ----------
Finance level3 statement 65
Wealth Management level2 lending 23
Mergers and Acqu level3 statement 356
SQL>
它的缺点LISTAGG
是,如果' 的结果超过 4000 个字符,它将失败(但是,再次,你将如何处理包含超过 500 个月的结果?)。
推荐阅读
- dependency-injection - 如何在 NestJS 中获取依赖树/图?
- laravel - 分页中的 onEachSide() 在 Laravel 6.16.0 中不起作用
- python - 如何使用 ccdproc 的 wcs_project 重新投影适合文件?
- macos - 如何在 macOS SwfitUI 中创建默认按钮?
- typescript - 如何在角度 6 中使用 mat stepper 组合多个表单组并发布到一个 api
- python - 使用 PIL 随机选择图像
- c++ - C ++尝试读取文件并输出到不同的文本文件
- css - 是否可以为 CSS 蒙版图像设置动画?
- pycharm - Pycharm:Numpy 安装包失败
- sql - 按 SQL 排序未按预期工作,我不知道它在做什么,但我想要一种简单的日期升序