MySQL - 带空字段的最小值和最大值
MySQL - MIN and MAX value with empty fields
我正在尝试编写一个 SQL 允许我 return 开始时间的最小值和结束时间的最大时间。我的问题是,在 table 中我可以有空行,当我在空字段上执行 MIN 时,它 return 给我一个空值。我不能做 begin_service! = ''
因为我可能没有值,在这种情况下我必须有一个空结果。这是我的 table :
app_id
function_id
begin_service
end_service
B125
12
B125
13
B125
54
C789
98
C789
12
06:00
18:00
C789
15
08:00
20:00
C789
78
我的 SQL :
SELECT app_id, MIN(begin_service), MAX(end_service)
FROM applications
GROUP BY app_id;
结果:
app_id
begin_service
begin_service
B125
C789
20:00
想要的结果:
app_id
begin_service
begin_service
B125
C789
06:00
20:00
你能帮帮我吗?
使用两个子查询获取每个 app_id
的空和非空最小值。将它们与 UNION
组合,然后取其最大值以选择非空值。
SELECT app_id, MAX(begin_service) AS begin_service, MAX(end_service) AS end_service
FROM (
SELECT app_id, MIN(begin_service) AS begin_service, MAX(end_service) AS end_service
FROM applications
WHERE begin_service != ''
GROUP BY app_id
UNION ALL
SELECT app_id, '', MAX(end_service)
FROM applications
WHERE begin_service = ''
GROUP BY app_id
) AS x
GROUP BY app_id
我正在尝试编写一个 SQL 允许我 return 开始时间的最小值和结束时间的最大时间。我的问题是,在 table 中我可以有空行,当我在空字段上执行 MIN 时,它 return 给我一个空值。我不能做 begin_service! = ''
因为我可能没有值,在这种情况下我必须有一个空结果。这是我的 table :
app_id | function_id | begin_service | end_service |
---|---|---|---|
B125 | 12 | ||
B125 | 13 | ||
B125 | 54 | ||
C789 | 98 | ||
C789 | 12 | 06:00 | 18:00 |
C789 | 15 | 08:00 | 20:00 |
C789 | 78 |
我的 SQL :
SELECT app_id, MIN(begin_service), MAX(end_service)
FROM applications
GROUP BY app_id;
结果:
app_id | begin_service | begin_service |
---|---|---|
B125 | ||
C789 | 20:00 |
想要的结果:
app_id | begin_service | begin_service |
---|---|---|
B125 | ||
C789 | 06:00 | 20:00 |
你能帮帮我吗?
使用两个子查询获取每个 app_id
的空和非空最小值。将它们与 UNION
组合,然后取其最大值以选择非空值。
SELECT app_id, MAX(begin_service) AS begin_service, MAX(end_service) AS end_service
FROM (
SELECT app_id, MIN(begin_service) AS begin_service, MAX(end_service) AS end_service
FROM applications
WHERE begin_service != ''
GROUP BY app_id
UNION ALL
SELECT app_id, '', MAX(end_service)
FROM applications
WHERE begin_service = ''
GROUP BY app_id
) AS x
GROUP BY app_id