MySQL MAX CASE WHEN和GROUP By

时间:2016-09-01 05:41:39

标签: mysql date

我目前在MySQL上遇到麻烦。我正试图获得最大的'结束',其中end< = timeend group by timeend。 目前我使用:

SELECT 
 timestart, 
 timeend,
 MAX(num),
 MIN(start) as start,
 (case when MAX(end)<=timeend then MAX(end) end)  AS end, value 
FROM table
GROUP BY timeend

表如下:(正如您可以看到,当值为null时,end大于timeend)

 timestart      timeend     num        start             end         value
08/15 09:46 | 08/15 10:07 | 1    | 08/15 09:48:33 | 08/15 09:48:49 | 15.3
08/15 09:46 | 08/15 10:07 | 2    | 08/15 09:48:55 | 08/15 09:49:11 | 15.3
08/15 09:46 | 08/15 10:07 | 3    | 08/16 08:00:00 | 08/16 08:00:00 | 
08/15 09:46 | 08/15 10:07 | 4    | 08/16 08:00:00 | 08/16 08:00:00 | 
08/15 09:46 | 08/15 10:07 | 5    | 08/16 08:00:00 | 08/16 08:00:00 | 
08/15 09:46 | 08/15 10:07 | 5    | 08/15 10:03:20 | 08/15 10:03:35 | 15.3
08/15 09:46 | 08/15 10:07 | 6    | 08/15 10:03:42 | 08/15 10:03:57 | 15.3
08/15 09:46 | 08/15 10:07 | 7    | 08/15 10:04:02 | 08/15 10:04:18 | 15.3
08/15 09:46 | 08/15 10:07 | 8    | 08/15 10:04:23 | 08/15 10:04:38 | 15.3
08/15 09:46 | 08/15 10:07 | 9    | 08/15 10:04:43 | 08/15 10:04:59 | 15.3
08/15 09:46 | 08/15 10:07 | 10   | 08/15 10:05:04 | 08/15 10:05:19 | 15.3
08/15 09:46 | 08/15 10:07 | 11   | 08/15 10:05:24 | 08/15 10:05:40 | 15.3
08/15 09:46 | 08/15 10:07 | 12   | 08/15 10:05:45 | 08/15 10:06:00 | 15.3
08/15 09:46 | 08/15 10:07 | 13   | 08/15 10:06:05 | 08/15 10:06:20 | 15.3

Result
08/15 09:46 | 08/15 10:07 | 13   | 08/15 09:48:33 | NULL | 15.3

The Result I expect:
08/15 09:46 | 08/15 10:07 | 13   | 08/15 09:48:33 | 08/15 10:06:20 | 15.3

1 个答案:

答案 0 :(得分:0)

SELECT 
  timestart,
  timeend,
  MAX(num) as num,
  MIN(start) as start,
  MAX(end) as end,
  value
FROM table 
WHERE end <= timeend 
GROUP BY timestart, timeend