我有一张表,其中包含一天内不同事件的行。
+------------+---------------------+---------------------+-----------+
| 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,则值为&00; 00:00:00'
现在我必须查询:
MIN(Firststart),其值为> ' 0000-00-00 00:00:00' (如果存在,否则' 00:00:00',) 和每个Logdate的SUM(Drivetime)。
通过使用下面的查询,我总是得到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
这是可能的,如果是这样,那么正确的语法是什么?
答案 0 :(得分:0)
试试这个:
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;
在SQL Fiddle上看到它。
答案 1 :(得分:0)
诀窍是使用NULLIF
在'0000-00-00 00:00:00'
aggreagate函数之前将所有MIN/MAX
字符串设为NULL,因为它会将它们排除在外。
聚合后,如果有空值,我们可以使用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