扁平大查询行

时间:2018-11-07 10:19:43

标签: sql google-bigquery

请帮助我解决此任务。我有这样的Google Big Query表:

| name | startDate  | endDate    |
| Bob  | 2018-01-01 | 2018-01-01 |
| Nick | 2017-12-29 | 2017-12-31 |

因此,我需要获得如下内容:

| name  | date       |
| Bob   | 2018-01-01 |
| Nick  | 2017-12-29 |
| Nick  | 2017-12-30 |
| Nick  | 2017-12-31 |

有可能吗?预先谢谢你。

3 个答案:

答案 0 :(得分:2)

WITH CTE as (
SELECT 'bob' name, date('2018-01-01') startDate, date('2018-01-01') endDate
UNION ALL SELECT 'Nick', date '2017-12-29' startDate, date('2017-12-31') endDate
),

CTE2 AS (
SELECT name, GENERATE_DATE_ARRAY(startDate, endDate, INTERVAL 1 DAY) AS date
FROM CTE
)

SELECT name, date
FROM CTE2,
UNNEST(date) as date

答案 1 :(得分:0)

您可以在此处使用日历表:

WITH dates AS (
    SELECT '2017-12-29' AS date_val UNION ALL
    SELECT '2017-12-30' UNION ALL
    SELECT '2017-12-31' UNION ALL
    SELECT '2018-01-01'
    -- and maybe other dates
)

SELECT
    t2.name,
    t1.date_val
FROM dates t1
INNER JOIN yourTable t2
    ON t1.date_val BETWEEN t2.startDate AND t2.endDate
ORDER BY
    t2.name,
    t1.date_val;

如果您的BigQuery版本不支持CTE,则可以将CTE作为子查询内联。也就是说,将dates替换为CTE本身的正文。

在实践中,您可能想生成一个日期序列(q.v. here),或者可能在数据库中维护一个专用的日历表。以上只是显示了查询本身的外观。

答案 2 :(得分:0)

或者只是

#standardSQL
SELECT name, date
FROM `project.dataset.table`, 
UNNEST(GENERATE_DATE_ARRAY(startDate, endDate)) date