sql - Redshift 不支持 rollup(), grouping() 函数

标签 sql group-by amazon-redshift rollup

尝试将 Teradata bteq SQL 脚本转换为 redshift SQL。我目前的redshift Postgres版本是8.0.2,redshift版本是1.0.1499。当前版本的 redshift 不支持 rollup(), grouping() 函数。如何克服和解决这种情况。它们的等效 Redshift 函数是什么?谁能用一些例子解释如何做?

示例 Teradata SQL-

select 
PRODUCT_ID,CUST_ID, 
GROUPING (PRODUCT_ID), 
GROUPING (CUST_ID), 
row_number over (order by PRODUCT_ID,CUST_ID) AS "ROW_OUTPUT_NUM"
from products 
group by rollup(PRODUCT_ID,CUST_ID);

需要将上面的sql查询转换成Redshift

最佳答案

手动实现 ROLLUP

一旦 Redshift 当前无法识别 ROLLUP 子句,您必须以硬方式实现此分组技术。

带 1 个参数的 ROLLUP

使用 ROLLUP Ex。 PostgreSQL

SELECT column1, aggregate_function(*)
FROM some_table
GROUP BY ROLLUP(column1)

等效实现

-- First, the same GROUP BY without the ROLLUP
-- For efficiency, we will reuse this table
DROP TABLE IF EXISTS tmp_totals;
CREATE TEMP TABLE tmp_totals AS
  SELECT column1, aggregate_function(*) AS total1
  FROM some_table
  GROUP BY column1;

-- Show the table 'tmp_totals'
SELECT * FROM tmp_totals

UNION ALL

-- The aggregation of 'tmp_totals'
SELECT null, aggregate_function(total1) FROM tmp_totals

ORDER BY 1

示例输出

Country  | Sales
-------- | -----
Poland   | 2
Portugal | 4
Ukraine  | 3
null     | 9

带有 2 个参数的 ROLLUP

使用 ROLLUP Ex。 PostgreSQL

SELECT column1, column2, aggregate_function(*)
FROM some_table
GROUP BY ROLLUP(column1, column2);

等效实现

-- First, the same GROUP BY without the ROLLUP
-- For efficiency, we will reuse this table
DROP TABLE IF EXISTS tmp_totals;
CREATE TEMP TABLE tmp_totals AS
  SELECT column1, column2, aggregate_function(*) AS total1
  FROM some_table
  GROUP BY column1, column2;

-- Show the table 'tmp_totals'
SELECT * FROM tmp_totals

UNION ALL

-- The sub-totals of the first category
SELECT column1, null, sum(total1) FROM tmp_totals GROUP BY column1

UNION ALL

-- The full aggregation of 'tmp_totals'
SELECT null, null, sum(total1) FROM tmp_totals

ORDER BY 1, 2;

示例输出

Country  | Segment  | Sales
-------- | -------- | -----
Poland   | Premium  | 0
Poland   | Base     | 2
Poland   | null     | 2     <- sub total
Portugal | Premium  | 1
Portugal | Base     | 3
Portugal | null     | 4     <- sub total
Ukraine  | Premium  | 1
Ukraine  | Base     | 2
Ukraine  | null     | 3     <- sub total
null     | null     | 9     <- grand total

关于sql - Redshift 不支持 rollup(), grouping() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47507231/

相关文章:

amazon-redshift - Redshift : Unnest subquery's result on leader is not supported

php - 多页 session 存储在数据库中

mysql - SQL Count() 列值

sql/c#错误: Cannot insert explicit value for identity column when IDENTITY_INSERT is set to off

Mysql递归查询——获取所有父子关系

Python:创建一个根据条件变化的递增变量

php - 使用 group by 为报告(订单报告)编写单个 mysql 查询

psycopg2 - 为什么 psycopg2 不允许我们在同一连接中打开多个服务器端游标?

mysql - SELECT IF 行到多列

java - 当用户密码中包含 # 字符时,Redshift JDBC 连接身份验证失败