我需要创建两行包含总计,而不是典型的总计行。总计和平均值。
我正在使用基本 SQL 创建报告,并且正在使用 Oracle 数据库,但我没有使用任何 PL/SQL。
我目前正在使用 Group By Grouping Sets 来生成报告,其中一行是包含总计的行。这些总计目前正在使用 SUM(column) 生成,使用聚合和分析函数的组合来生成我的一行总计。我需要的是在同一数据集上产生总计的另一行。实现这一目标的最佳方法是什么?当我说得最好时,我正在考虑我的数据库上的负载,因为此报告将针对大量数据运行。我的例子非常基本,但可以理解。
下面是一些使用 Group By Grouping Sets 生成总计总计的示例数据。缺少的是我想要生成平均值的总计下方的另一行。
WITH sample_data AS
(
SELECT 1 AS client_key, 'NASA' AS client, 8 AS SPACESHIPS_SOLD, 105585 AS REVENUE FROM DUAL UNION ALL
SELECT 2 AS client_key, 'Origin' AS client, 3 AS SPACESHIPS_SOLD, 36581 AS REVENUE FROM DUAL UNION ALL
SELECT 3 AS client_key, 'SpaceX' AS client, 7 AS SPACESHIPS_SOLD, 83851 AS REVENUE FROM DUAL
)
SELECT sd.client_key
, CASE WHEN grouping(sd.client) = 0 THEN to_char(sd.client) ELSE 'Grand Totals -->' END AS client
, SUM(sd.spaceships_sold) AS spaceships_sold
, SUM(sd.revenue) AS revenue
FROM sample_data sd
GROUP BY
GROUPING SETS (
(sd.client_key, sd.client),
()
)
;
我正在寻找的示例图像。
以下是我对如何获得这个额外的 Totals Row 的想法,但不确定这是否是为了获得这个我应该做的。似乎令人费解,我一直认为这应该是 Grouping Sets 的现有功能。在下面的方法中,我使用 CTE 和 UNION ALL 在我的数据集底部获取额外的平均值总计,如下面的屏幕截图所示。
上面屏幕截图中的 SQL。
WITH sample_data AS
(
SELECT 1 AS client_key, 'NASA' AS client, 8 AS SPACESHIPS_SOLD, 105585 AS REVENUE FROM DUAL UNION ALL
SELECT 2 AS client_key, 'Origin' AS client, 3 AS SPACESHIPS_SOLD, 36581 AS REVENUE FROM DUAL UNION ALL
SELECT 3 AS client_key, 'SpaceX' AS client, 7 AS SPACESHIPS_SOLD, 83851 AS REVENUE FROM DUAL
)
, data_Sum_totals AS
(
SELECT sd.client_key
, CASE WHEN grouping(sd.client) = 0 THEN to_char(sd.client) ELSE 'Grand Totals -->' END AS client
, SUM(sd.spaceships_sold) AS spaceships_sold
, SUM(sd.revenue) AS revenue
FROM sample_data sd
GROUP BY
GROUPING SETS (
(sd.client_key, sd.client),
()
)
)
, data_Avg_totals AS
(
SELECT grouping(sd.client_key) AS row_group
, sd.client_key
, CASE WHEN grouping(sd.client) = 0 THEN to_char(sd.client) ELSE 'AVG Totals -->' END AS client
, AVG(sd.spaceships_sold) AS spaceships_sold
, AVG(sd.revenue) AS revenue
FROM sample_data sd
GROUP BY
GROUPING SETS (
(sd.client_key, sd.client),
()
)
HAVING grouping(sd.client_key) = 1 /* This line restricts the output to only give me the Totals row */
)
SELECT client_key, client, spaceships_sold, revenue
FROM data_Sum_totals
UNION ALL
SELECT client_key, client, spaceships_sold, revenue
FROM data_Avg_totals
;