我面临的问题是我在汇总成本的同时试图仅在两个不同的列中显示不同的名称。
我尝试做MAX和Order By,但似乎没有一个与我要创建的内容相匹配,否则我可能做错了。
例如,我正在寻找的示例如下:
(提取之前的数据确实与每一行都关联了日期,但是对于提取的日期,我并不在意)
Category | Game | Sold
FPS | Battlefield 5| 12
FPS | Division 2 | 15
FPS | Black Ops | 5
Strategy | TW:WH2 | 13
Strategy | TW:WH2 | 17
FPS | Battlefield 5| 15
FPS | Division 2 | 10
Strategy | Satisfactory | 12
我希望它看起来像是:
Category | Game | Sold
FPS | Battlefield 5| 27
| Division 2 | 25
| Black Ops | 5
Strategy | TW:WH2 | 30
| Satisfactory | 12
这是可以做到的,因为我相信我以前已经看过它,但是我不确定如何编写代码来创建它。
任何帮助将不胜感激!
-Maykid
答案 0 :(得分:3)
以下是用于BigQuery标准SQL
#standardSQL
SELECT category,
ARRAY_AGG(STRUCT(game AS game, sold AS sold) ORDER BY sold DESC) sale
FROM (
SELECT category, game, SUM(sold) sold
FROM `project.dataset.table`
GROUP BY category, game
)
GROUP BY category
您可以使用问题中的示例数据来进行测试,如上示例所示
#standardSQL
WITH `project.dataset.table` AS (
SELECT 'FPS' category, 'Battlefield 5' game, 12 sold UNION ALL
SELECT 'FPS', 'Division 2', 15 UNION ALL
SELECT 'FPS', 'Black Ops', 5 UNION ALL
SELECT 'Strategy', 'TW:WH2', 13 UNION ALL
SELECT 'Strategy', 'TW:WH2', 17 UNION ALL
SELECT 'FPS', 'Battlefield 5', 15 UNION ALL
SELECT 'FPS', 'Division 2', 10 UNION ALL
SELECT 'Strategy', 'Satisfactory', 12
)
SELECT category,
ARRAY_AGG(STRUCT(game AS game, sold AS sold) ORDER BY sold DESC) sale
FROM (
SELECT category, game, SUM(sold) sold
FROM `project.dataset.table`
GROUP BY category, game
)
GROUP BY category
有结果