带换行符的SQL Group Concat

时间:2019-02-06 17:19:48

标签: sql google-bigquery

我正在尝试格式化一些数据,并将其制成逗号分隔的文件,但是我不确定如何在其中添加换行符。下面是查询:

select group_concat(line,',') as data
from (select concat(cast(date as string), ',',
                    cast(data_1 as string), ',',
                    cast(data_2 as string), ',',
                    cast(data_3 as string), ',',
                    cast(data_4 as string)
                   ) as line
      from [project:dataset.table]
      order by 2 desc
     )

我该如何包含换行符?

谢谢

1 个答案:

答案 0 :(得分:2)

以下是用于BigQuery标准SQL

注意:强烈建议使用标准SQL。如果由于某些原因您仍然使用旧版SQL,请考虑使用Migrating to Standard SQL

#standardSQL
SELECT STRING_AGG(CONCAT(
        CAST(date_col AS STRING), ',',
        CAST(data1 AS STRING), ',',
        CAST(data2 AS STRING)
    ), '\n' ORDER BY date_col) payload
FROM `project.dataset.table` 

#standardSQL
SELECT STRING_AGG(CONCAT(
        CAST(date_col AS STRING), ',',
        CAST(data1 AS STRING), ',',
        CAST(data2 AS STRING)
    ), '''
''' ORDER BY date_col) payload
FROM `project.dataset.table` 

如果将以上任何内容应用于以下虚拟数据

WITH `project.dataset.table` AS (
    SELECT CURRENT_DATE() AS date_col, 123 AS data1, 456 AS data2 UNION ALL
    SELECT '2019-02-01', 222, 333 UNION ALL
    SELECT '2019-02-02', 444, 444 
)

结果是

2019-02-01,222,333
2019-02-02,444,444
2019-02-06,123,456   

注意-由于ORDER BY date_col函数中的STRING_AGG()子句,结果按date_col排序