我想用T1中的值替换T1中属性列中的值。如果T2中的sub_id为NULL,则对于ID为T2的所有行,将T1中的 f 值替换为 t ,否则仅对具有sub_id的行执行此操作。
下面是虚拟表格和我得到的结果。
WITH T1 AS ( SELECT 1 AS id, 2 as sub_id, '2017-08-20' AS date, 'f' AS attribute UNION ALL
SELECT 1, 3 as sub_id, '2017-08-19', 'f' UNION ALL
SELECT 1, 4 as sub_id,'2017-08-18', 'f' UNION ALL
SELECT 2, 5 as sub_id,'2017-08-20', 'f' UNION ALL
SELECT 2, 6 as sub_id,'2017-08-19', 'f'
),
T2 AS (
SELECT 1 AS id, null as sub_id, '2017-08-19' AS date, '2017-08-25' AS date_end, 't' AS attribute UNION ALL
SELECT 2, 5 as sub_id,'2017-08-19', '2017-08-25' AS date_end, 't' UNION ALL
SELECT 2, 6 as sub_id,'2017-08-19', '2017-08-25' AS date_end, 't'
)
SELECT
a.id,
a.date,
a.sub_id,
COALESCE(b.attribute, a.attribute) as attribute
FROM T1 AS a
LEFT JOIN T2 AS b
ON a.id = b.id AND a.date >= b.date AND a.date <= b.date_end
AND a.sub_id = case when b.sub_id is not null then a.sub_id end
在上面的结果中,我想在所有符合条件的行中使用 t 值的属性列。 我用另一个子查询实现了我想要的东西:
WITH T1 AS ( SELECT 1 AS id, 2 as sub_id, '2017-08-20' AS date, 'f' AS attribute UNION ALL
SELECT 1, 3 as sub_id, '2017-08-19', 'f' UNION ALL
SELECT 1, 4 as sub_id,'2017-08-18', 'f' UNION ALL
SELECT 2, 5 as sub_id,'2017-08-20', 'f' UNION ALL
SELECT 2, 6 as sub_id,'2017-08-19', 'f'
),
T2 AS (
SELECT 1 AS id, null as sub_id, '2017-08-19' AS date, '2017-08-25' AS date_end, 't' AS attribute UNION ALL
SELECT 2, 5 as sub_id,'2017-08-19', '2017-08-25' AS date_end, 't' UNION ALL
SELECT 2, 6 as sub_id,'2017-08-19', '2017-08-25' AS date_end, 't'
) ,
adv_level AS ( SELECT
a.id,
a.date,
a.sub_id,
COALESCE(b.attribute, a.attribute) as attribute
FROM T1 AS a
LEFT JOIN T2 AS b
ON a.id = b.id AND a.date >= b.date AND a.date <= b.date_end AND a.sub_id = case when b.sub_id is not null then a.sub_id end)
SELECT
a.id,
a.date,
a.sub_id,
COALESCE(b.attribute, a.attribute) as attribute
FROM adv_level AS a
LEFT JOIN T2 AS b
ON a.id = b.id AND a.date >= b.date AND a.date <= b.date_end
但有没有办法只做一次?