首页 > 解决方案 > 通过折叠 SQL 中的行来转换数据

问题描述

我很难处理当前显示第一个表格的行的数据集,我想将其更改为看起来像底部表格(见图)。

这在 SQL 中可能吗?

示例数据::

示例数据

在客户没有购买特定产品的情况下,它应该只返回 null。表名=dbo.sales

有谁知道如何改变这个?我希望我已经提供了足够的信息来让我朝着正确的方向前进。最好的,克里斯汀

标签: sqlpivot

解决方案


您可以尝试 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

推荐阅读