根据时间范围

时间:2017-06-27 15:07:31

标签: sql google-bigquery

我们说我有T1:

id         date        attribute
1        2017-04-20        t
1        2017-04-19        t
1        2017-04-18        t
2        2017-04-20        t
2        2017-04-19        f

我也有T2:

 id         date        date_end    attribute
  1        2017-04-19   2017-04-25      f

我想要的是获取一个新表,其中包含来自T1的数据,但如果两个表中都有匹配的ID,则将T2中的属性值替换为T2中定义的日期范围中的T2中的属性值。

结果如下:

id         date        attribute
    1        2017-04-20        f
    1        2017-04-19        f
    1        2017-04-18        t
    2        2017-04-20        t
    2        2017-04-19        f

我想出的是:

SELECT t1.id, t1.date,
CASE WHEN max(T2.id) IS NULL THEN T1.attribute ELSE T2.attribute END 
FROM T1
LEFT JOIN T2 using (id)

无法弄清楚如何更改特定范围的属性。 任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:3)

我认为这只是LEFT JOIN COALESCE()

SELECT t1.id, t1.date,
       COALESCE(t2.attribute, t1.attribute) as attribute
FROM T1 LEFT JOIN
     T2 
     ON t1.id = t2.id AND
        t1.date >= t2.date and t1.date <= t2.date_end;

答案 1 :(得分:2)

对于BigQuery Standard SQL

  
#standardSQL
SELECT
  a.id,
  a.date,
  CASE 
    WHEN a.date BETWEEN b.date AND b.date_end THEN b.attribute
    ELSE a.attribute
  END AS attribute
FROM T1 AS a
LEFT JOIN T2 AS b
ON a.id = b.id

您可以使用问题中的示例数据进行/测试

#standardSQL
WITH T1 AS (
  SELECT 1 AS id, '2017-04-20' AS date, 't' AS attribute UNION ALL
  SELECT 1, '2017-04-19', 't' UNION ALL
  SELECT 1, '2017-04-18', 't' UNION ALL
  SELECT 2, '2017-04-20', 't' UNION ALL
  SELECT 2, '2017-04-19', 'f' 
),
T2 AS (
  SELECT 1 AS id, '2017-04-19' AS date, '2017-04-25' AS date_end, 'f' AS attribute
)
SELECT
  a.id,
  a.date,
  CASE 
    WHEN a.date BETWEEN b.date AND b.date_end THEN b.attribute
    ELSE a.attribute
  END AS attribute
FROM T1 AS a
LEFT JOIN T2 AS b
ON a.id = b.id
-- ORDER BY 1,2 DESC