从 SQL 到 SPL:Create columns from distinct values of a column

SQLSPLCreate columns from distinct values of a column

某库表记录了不同产品每个月的销售额,其中产品的值未知。

product

month

amount

AA

1

100

AA

1

150

AA

2

200

AA

2

120

BB

2

180

BB

2

220

CC

3

80

现在要对产品、月份分组,对销售额求和,再将产品由行转列。

month

AA

BB

CC

1

250



2

320

400


3



80

SQL

SELECT format(
$f$
SELECT * FROM crosstab(
   $q$
   SELECT month, product, sum(amount)
   FROM   ventas
   GROUP  BY 1, 2
   ORDER  BY 1, 2
   $q$
 , $c$VALUES (%s)$c$
   ) AS ct(month int, %s);
$f$  -- end dynamic query string
            , string_agg(quote_literal(sub.product), '), (')
            , string_agg(quote_ident  (sub.product), ' int, ') || ' int'
                 )
FROM  (SELECT DISTINCT product FROM ventas ORDER BY 1) sub;

SQL进行行转列时必须写出列名,要先用上面的预处理 SQL 动态生成实际 SQL,再执行实际 SQL,步骤繁琐。用存储过程可以将两步合并为一步,但结构更复杂。SPL 的行列转换函数不必写出列名:https://try.esproc.com/splx?4i8


 A

1

$select * from ventas.txt

2

=A1.pivot@s(month;product,sum(amount))

A1:加载数据。

A2:保持月份列不变,将产品由行转为列名,金额为列值。函数 pivot 用于行转列,@s 表示转换时进行聚合运算。

问题来源:https://stackoverflow.com/questions/78157389/create-columns-from-distinct-values-of-a-column