sql - 通过折叠 SQL 中的行来转换数据
问题描述
我很难处理当前显示第一个表格的行的数据集,我想将其更改为看起来像底部表格(见图)。
这在 SQL 中可能吗?
示例数据::
在客户没有购买特定产品的情况下,它应该只返回 null。表名=dbo.sales
有谁知道如何改变这个?我希望我已经提供了足够的信息来让我朝着正确的方向前进。最好的,克里斯汀
解决方案
您可以尝试 LISTAGG 和 REGEXP_SUBSTR 的组合
WITH TAB AS(
SELECT customer,
LISTAGG (product, ',')
WITHIN GROUP (ORDER BY customer) str
FROM table
GROUP BY customer
)
select customer,
regexp_substr(str, '[^,]*,', 1, 1) as product1
,regexp_substr(str,'[^,]+',1,2) as product2
,regexp_substr(str,'[^,]+',1,3) as product3
,regexp_substr(str,'[^,]+',1,4) as product4
,regexp_substr(str,'[^,]+',1,5) as product5
,regexp_substr(str,'[^,]+',1,6) as product6
,regexp_substr(str,'[^,]+',1,7) as product7
,regexp_substr(str,'[^,]+',1,8) as product8
,regexp_substr(str,'[^,]+',1,9) as product9
,regexp_substr(str,'[^,]+',1,10) as product10
from TAB
推荐阅读
- ruby-on-rails - 如何更改多态模型的外部类型
- sapui5 - OpenUi5 上的较小元素
- sql - MSSQL - 视图中的 row_number() 显示意外
- networking - 使用 IP_ADD_MEMBERSHIP 在新创建的接口上加入多播组
- wordpress - 如何使用 WP_Query 显示自定义类别的最新帖子?
- python - 使用 json 列从 mysql 导入数据到弹性搜索
- sql-server - ODBC--调用失败(试图在 MS Access 中打开表)
- ios - 如何在其父视图范围之外启用视图的触摸?
- tfs - TFS 2017 (v15) 如何配置发布环境和特定构建代理之间的关联
- image - 硬代码降价图像