【问题标题】:MySQL - MIN and MAX value with empty fieldsMySQL - 具有空字段的 MIN 和 MAX 值
【发布时间】:2021-09-11 20:18:57
【问题描述】:

我正在尝试编写一个 SQL,它允许我返回开始时间的最小值和结束时间的最大时间。我的问题是,在表中我可以有空行,当我在空字段上执行 MIN 时,它会返回一个空值。我不能begin_service! = '' 因为我可能没有值,在这种情况下我必须有一个空结果。这是我的桌子:

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

你能帮帮我吗?

【问题讨论】:

  • c789 的最短时间是 06:00 吗? 06:00 属于 C783。
  • 抱歉,打错了
  • begin_service 和 end_service 的数据类型是什么
  • 这是一个字符串@AmitVerma

标签: mysql max min


【解决方案1】:

使用两个子查询来获取每个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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2015-04-05
    • 2016-08-27
    • 1970-01-01
    • 2012-10-28
    • 2017-06-10
    • 2012-08-26
    相关资源
    最近更新 更多