У меня есть данные в двух таблицах, используя 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
Как мне получить ответ, как показано ниже, с помощью union?
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
рассмотрите возможность голосования за полезные / полезные ответы: o)