SQL BIG QUERY - Одна строка в несколько строк - PullRequest
0 голосов
/ 18 марта 2020

Я пытаюсь разбить 1 строку на несколько строк.

Пример:

This is what I have :
Row date           enquiry calls enuiryL callsL
1   2020-01-01      25     5      45     20

This is what I need:
Row date          Type        Thisyear   LastYear
1   2020-01-01    enquiry        25         45
2   2020-01-01    Calls          5          20

Любая помощь приветствуется. Спасибо!

Ответы [ 3 ]

1 голос
/ 18 марта 2020

Вы можете использовать массивы и unnest():

select row_number() over (order by date, type desc) as row,
       t.date, el.type, el.thisyear, el.lastyear
from t cross join
     unnest(array[struct('enquiry' as type, enquiry as thisyear, enquiryl as lastyear),
                  struct('calls' as type, calls as thisyear, callsl as lastyear)
                 ]
           ) el;
0 голосов
/ 18 марта 2020

Ниже для BigQuery Standard SQL

#standardSQL
SELECT date, type, thisyear, lastyear
FROM (
  SELECT date, 
    [
      STRUCT('enquiry' AS type, enquiry AS thisyear, enquiryl AS lastyear),
      ('calls', calls, callsl)
    ] lines
  FROM `project.dataset.table`
) t, t.lines   

с выводом

Row date        type        thisyear    lastyear     
1   2020-01-01  enquiry     25          45   
2   2020-01-01  calls       5           20   
0 голосов
/ 18 марта 2020

Вы можете просто использовать union all:

select row_number() over(order by row, type) row, date, type, this_year, last_year
from (
    select row, date, 'enquiry' type, enquiry this_year, enquiryL last_year
    union all
    select row, date, 'calls' type, calls, callsL
) t
order by row
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...