带条件的聚合函数

vhmi4jdf  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(403)

我有一个表,其中包含一天中不同事件的行。

+------------+---------------------+---------------------+-----------+
|  Logdate   |      Firstart       |      Laststop       | Drivetime |
+------------+---------------------+---------------------+-----------+
| 2018-04-01 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 00:36:25  |
| 2018-04-01 | 2018-04-01 07:43:12 | 2018-04-01 09:43:12 | 00:21:23  |
| 2018-04-01 | 2018-04-01 09:53:27 | 2018-04-01 14:45:11 | 00:54:11  |
+------------+---------------------+---------------------+-----------+

我必须按天分组,得到firststart的最小值。
如果该事件不存在firststart,则值为“0000-00-00:00:00”。
现在我要问的是:
min(firststart),值大于'0000-00-00 00:00:00'(如果存在,否则为'0000-00-00:00:00',)和每个日志日期的总和(行车时间)。
通过使用下面的查询,我总是得到'0000-00-00:00:00'作为min(firstart),但我想得到'2018-04-01 07:43:12'作为该值,

SELECT 
 Logdate,
 MIN(Firststart) AS Firststart,
 MAX(Laststop) AS Laststop,
 SEC_TO_TIME(SUM(TIME_TO_SEC(Drivetime))) AS Drivetime
FROM Logevents
WHERE Logdate >= "2018-04-01"
GROUP BY Logdate

这可能吗?如果可能,正确的语法是什么?

tzcvj98z

tzcvj98z1#

诀窍是使用 NULLIF 使全部为空 '0000-00-00 00:00:00' 前面的字符串 MIN/MAX 聚集函数,因为它将排除它们。
在聚合之后,如果有空值,我们可以使用 ISNULL 将它们转换回 '0000-00-00 00:00:00' 字符串。

select 
    Logdate, 
    isnull(MIN(nullif(Firststart, '0000-00-00 00:00:00')), '0000-00-00 00:00:00') Firststart, 
    isnull(MAX(nullif(Laststop, '0000-00-00 00:00:00')), '0000-00-00 00:00:00')  Laststop, 
    cast(dateadd(ss, SUM(datediff(ss, 0, Drivetime)), 0) as time(0)) Drivetime
from x
group by Logdate
gmol1639

gmol16392#

试试这个:

SELECT Logdate, MAX(Firststart) AS Firststart, MAX(Laststop) AS Laststop,
  SEC_TO_TIME(SUM(TIME_TO_SEC(A.Drivetime))) AS Drivetime
FROM
    (SELECT
      Logdate, MIN(Firststart) AS Firststart, MAX(Laststop) AS Laststop,
      SEC_TO_TIME(SUM(TIME_TO_SEC(Drivetime))) AS Drivetime
    FROM Logevents
    WHERE Firststart>'0000-00-00 00:00:00' 
    GROUP BY Logdate
    UNION
    SELECT
      Logdate, MIN(Firststart) AS Firststart, MAX(Laststop) AS Laststop,
      SEC_TO_TIME(SUM(TIME_TO_SEC(Drivetime))) AS Drivetime
    FROM Logevents
    WHERE Firststart='0000-00-00 00:00:00'
    GROUP BY Logdate) A
GROUP BY A.Logdate;

看看它在sqlfiddle上运行。

相关问题