PostgreSQL 中,GROUPING SETS、CUBE 和 ROLLUP 的功能,允许在查询中更灵活地生成聚合结果,而不需要多次重写查询或使用复杂的 UNION 语句。这些功能在数据分析中特别有用,因为它们允许你以不同的维度对数据进行分组和聚合。
1、测试表及数据准备
1.1、json_to_recordset内置函数
It joins two functions into a single FROM target. json_to_recordset() is instructed to return three columns, the first integer , the second text and the third text.
The result of generate_series() is used directly. The ORDER BY clause sorts the column values as integers.
在 PostgreSQL 中 json_to_recordset 的内置函数,主要目的是将 JSON 数据转换为 SQL 可以查询的记录集(recordset)或表格式
1.2、创建测试表
CREATE table t_sales_table
as
SELECT *
FROM ROWS FROM
(
json_to_recordset('[{"sales":10,"b":"foo","size":"L"},{"sales":"20","b":"bar","size":"M"},{"sales":15,"b":"foo","size":"M"},{"sales":5,"b":"bar","size":"L"},{"sales":3,"b":"super","size":"L"}]')
AS ( b TEXT,size TEXT,sales INTEGER),
generate_series(1, 5)
) AS T1 (brand, c_size, c_qty,id)
ORDER BY id;
select * from t_sales_table;
superdb=# select * from t_sales_table;
brand | c_size | c_qty | id
-------+--------+-------+----
foo | L | 10 | 1
bar | M | 20