gpt4 book ai didi

mysql - 合并 UNION ALL 行以删除 NULL 值

转载 作者:太空宇宙 更新时间:2023-11-03 10:47:55 28 4
gpt4 key购买 nike

SELECT journey.id, TIME_FORMAT(ADDTIME(journey.departure, SEC_TO_TIME(SUM(l1.elapsed))), '%H:%i') AS departure, null AS arrival
FROM journey
INNER JOIN journey_day ON journey_day.journey = journey.code
INNER JOIN pattern ON pattern.code = journey.pattern
INNER JOIN link l1 ON l1.section = pattern.section AND l1.stop = "370023139"
INNER JOIN link l2 ON l2.section = pattern.section AND l2.id <= l1.id
WHERE journey.service = "11-252-_-y08-1" AND journey_day.day = 1 AND journey.code NOT IN (SELECT journey
FROM journey_non_operation
WHERE "2015-03-01" BETWEEN date_start AND date_end) AND pattern.direction = "outbound"
GROUP BY journey.id

UNION ALL

SELECT journey.id, null AS departure, TIME_FORMAT(ADDTIME(journey.departure, SEC_TO_TIME(SUM(l1.elapsed))), '%H:%i') AS arrival
FROM journey
INNER JOIN journey_day ON journey_day.journey = journey.code
INNER JOIN pattern ON pattern.code = journey.pattern
INNER JOIN link l1 ON l1.section = pattern.section AND l1.stop = "1000DEHS7812"
INNER JOIN link l2 ON l2.section = pattern.section AND l2.id <= l1.id
WHERE journey.service = "11-252-_-y08-1" AND journey_day.day = 1 AND journey.code NOT IN (SELECT journey
FROM journey_non_operation
WHERE "2015-03-01" BETWEEN date_start AND date_end) AND pattern.direction = "outbound"
GROUP BY journey.id

上面是两个查询,它们的结果由 UNION ALL 子句合并。您会注意到查询返回不同的列,一个称为“出发”,一个称为“到达”。为了让 UNION 与不同的列名一起工作,我必须给另一列 NULL ,这样它就不会忽略它,也不会将它包含在查询中。

我的问题是我的结果如下所示:

编号 |出发 |到达
1 asd NULL
2 asd NULL
3 asd NULL
4 asd NULL
5 NULL efg
6 NULL efg
7 NULL efg
8 NULL efg

如何合并行,以便 asdefg 根据 ID 匹配?

期望的结果:

编号 |出发 |到达
1 asd efg
2 asd efg
3 asd efg
4 asd efg

最佳答案

只需将聚合函数(最小值/最大值)应用于您的结果集。由于空值不包含在聚合中,您只会得到合并的结果:

select id, min(departure), min(arrival)
from (your query) as q
group by id

关于mysql - 合并 UNION ALL 行以删除 NULL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28795877/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com