Как найти самые высокие продажи, используя союз в BQ - PullRequest
0 голосов
/ 27 апреля 2018

У меня есть данные в двух таблицах, используя 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

1 Ответ

0 голосов
/ 27 апреля 2018
#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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...