簡體   English   中英

BigQuery 中的 PIVOT 能否生成一個“總計”列,聚合所有維度行?

[英]Can PIVOT in BigQuery generate a "total" column, aggregated across all dimension rows?

樣品表:

+---------+-------+---------+------+
| product | sales | quarter | year |
+---------+-------+---------+------|
| Kale    | 51    | Q1      | 2020 |
| Kale    | 23    | Q2      | 2020 |
| Kale    | 45    | Q3      | 2020 |
| Kale    | 3     | Q4      | 2020 |
| Kale    | 70    | Q1      | 2021 |
| Kale    | 85    | Q2      | 2021 |
| Apple   | 77    | Q1      | 2020 |
| Apple   | 0     | Q2      | 2020 |
| Apple   | 1     | Q1      | 2021 |
+---------+-------+---------+------+

我可以像這樣 pivot:

WITH t AS (
  SELECT 'Kale' as product, 51 as sales, 'Q1' as quarter, 2020 as year UNION ALL
  SELECT 'Kale', 23, 'Q2', 2020 UNION ALL
  SELECT 'Kale', 45, 'Q3', 2020 UNION ALL
  SELECT 'Kale', 3, 'Q4', 2020 UNION ALL
  SELECT 'Kale', 70, 'Q1', 2021 UNION ALL
  SELECT 'Kale', 85, 'Q2', 2021 UNION ALL
  SELECT 'Apple', 77, 'Q1', 2020 UNION ALL
  SELECT 'Apple', 0, 'Q2', 2020 UNION ALL
  SELECT 'Apple', 1, 'Q1', 2021
)
SELECT *
  FROM t
 PIVOT (
   sum(sales) as total
   FOR quarter in ('Q1', 'Q2')
)
 WHERE year = 2020

它給了我結果:

+---------+------+----------+----------+
| product | year | total_Q1 | total_Q2 |
+---------+------+----------+----------+
| Kale    | 2020 |       51 |       23 |
| Apple   | 2020 |       77 |        0 |
+---------+------+----------+----------+

現在我想添加“總計”列,其中包含跨產品和年份的所有銷售額。 結果將是:

+---------+------+----------+----------+-------+
| product | year | total_Q1 | total_Q2 | total |
+---------+------+----------+----------+-------+
| Kale    | 2020 |       51 |       23 |   122 |
| Apple   | 2020 |       77 |        0 |   77  |
+---------+------+----------+----------+-------+

這該怎么做? 是否可以使用 PIVOT 或我必須單獨 GROUP BY SQL 並將其加入 pivot 結果?

看看下面的查詢:您可以先使用分析 function 然后使用表 pivot 計算產品和年份的total以獲得您想要的結果。

WITH t AS (
  SELECT 'Kale' as product, 51 as sales, 'Q1' as quarter, 2020 as year UNION ALL
  SELECT 'Kale', 23, 'Q2', 2020 UNION ALL
  SELECT 'Kale', 45, 'Q3', 2020 UNION ALL
  SELECT 'Kale', 3, 'Q4', 2020 UNION ALL
  SELECT 'Kale', 70, 'Q1', 2021 UNION ALL
  SELECT 'Kale', 85, 'Q2', 2021 UNION ALL
  SELECT 'Apple', 77, 'Q1', 2020 UNION ALL
  SELECT 'Apple', 0, 'Q2', 2020 UNION ALL
  SELECT 'Apple', 1, 'Q1', 2021
)
SELECT * FROM (
  SELECT *, SUM(sales) OVER (PARTITION BY product, year) AS total FROM t
) PIVOT (SUM(sales) total FOR quarter IN ('Q1', 'Q2'))
WHERE year = 2020
;

output:

在此處輸入圖像描述

考慮以下方法

select * from (
  select * from your_table union all
  select product, sum(sales), 'Year', year 
  from your_table
  group by product, year
)
pivot (sum(sales) as total for quarter in ('Year', 'Q1', 'Q2'))
where year = 2020    

如果應用於您問題中的示例數據 - output 是

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM