google-bigquery - 如何在 BQ 中使用 union 找到最高销售额
问题描述
我有两个表中的数据,使用联合我如何获得每年最高的销售额?
with table1 as(
select "ProductA" as Product, 80000 as units_sold,"2016" as year union all
select "ProductB" as Product, 75000 as units_sold,"2016" as year union all
select "ProductC" as Product, 15000 as units_sold,"2016" as year
),
table2 as(
select "ProductA" as Product, 60000 as units_sold,"2017" as year union all
select "ProductB" as Product, 120000 as units_sold,"2017" as year union all
select "ProductC" as Product, 70000 as units_sold,"2017" as year
)
select * from table1 union all select * from table2
如何使用联合得到如下答案?
Product units_sold year
ProductA 80000 2016
ProductB 120000 2017
解决方案
#standardSQL
WITH table1 AS(
SELECT "ProductA" AS Product, 80000 AS units_sold,"2016" AS year UNION ALL
SELECT "ProductB" AS Product, 75000 AS units_sold,"2016" AS year UNION ALL
SELECT "ProductC" AS Product, 15000 AS units_sold,"2016" AS year
), table2 AS(
SELECT "ProductA" AS Product, 60000 AS units_sold,"2017" AS year UNION ALL
SELECT "ProductB" AS Product, 120000 AS units_sold,"2017" AS year UNION ALL
SELECT "ProductC" AS Product, 70000 AS units_sold,"2017" AS year
)
SELECT ARRAY_AGG(STRUCT(Product, units_sold) ORDER BY units_sold DESC)[OFFSET(0)].*, year
FROM (
SELECT Product, year, SUM(units_sold) units_sold
FROM (
SELECT * FROM table1 UNION ALL
SELECT * FROM table2
)
GROUP BY Product, year
)
GROUP BY year
ORDER BY year
推荐阅读
- java - JPA休眠一对多无限循环双向关系问题
- python - 如何编写从两个不同大小的数据帧中提取参数的向量化函数
- excel - VBA循环动态命名范围
- algorithm - 通过多个元素进行二分搜索
- javascript - 如何处理包含 null 的 JavaScript 对象(解析的 JSON)?
- c++ - 从文件中获取值并打印平均值、最大值和最小值的代码不起作用
- c++ - openCV - 从使用 hWND C++ 的窗口中使用 matchTemplate()
- python - 从 CSV 文件列表生成 Pandas DataFrames
- docker - Docker swarm 与 flow-proxy 和letsencrypt
- lua - 如何删除 pandoc 引用周围的括号?