我不知道怎样才能得到这些信息。
这是我的问题
SELECT
CAST(reports.report_creation_datetime AS DATE) AS report_date,
MIN(CAST(reports.report_creation_datetime AS TIME)) AS work_start, <--- I want to get id of this row
MAX(CAST(reports.report_creation_datetime AS TIME)) AS work_end <--- and this
FROM reports
WHERE reports.report_creation_datetime >= '2016-02-01'
AND reports.report_creation_datetime < LAST_DAY('2016-02-01') + INTERVAL 1 DAY
GROUP BY CAST(reports.report_creation_datetime AS DATE)
样本数据
---reports table
report_id report_creation_datetime
------------------------------------
82 2016-02-01 07:20:00
80 2016-02-01 10:30:00
85 2016-02-01 17:00:00
88 2016-02-02 08:00:00
87 2016-02-02 16:00:00
81 2016-02-03 10:50:00
我想得到
---expected result
report_date work_start wstart_id ...
-------------------------------------------------------
2016-02-01 07:20:00 82 ...
2016-02-02 08:00:00 88 ...
2016-02-03 10:50:00 81 ...
...
2016-02-29 07:30:00 199 ...
我想这样的子查询
其中日期=分钟(日期)
但这是不对的
最佳答案
有两种不同的方法可以做到这一点。您可以在两个子查询中使用join
将表返回到自身。您可以使用aggregation
。
也许最简单的解决方案是两个相关的子查询:
SELECT
CAST(r.report_creation_datetime AS DATE) AS report_date,
MIN(CAST(r.report_creation_datetime AS TIME)) AS work_start,
(SELECT id FROM reports r2
WHERE CAST(r.report_creation_datetime AS DATE) = CAST(r2.report_creation_datetime AS DATE)
ORDER BY r2.report_creation_datetime
LIMIT 1) work_start_id,
MAX(CAST(reports.report_creation_datetime AS TIME)) AS work_end,
(SELECT id FROM reports r3
WHERE CAST(r.report_creation_datetime AS DATE) = CAST(r3.report_creation_datetime AS DATE)
ORDER BY r3.report_creation_datetime DESC
LIMIT 1) work_end_id
FROM reports r
WHERE r.report_creation_datetime >= '2016-02-01'
AND r.report_creation_datetime < LAST_DAY('2016-02-01') + INTERVAL 1 DAY
GROUP BY CAST(r.report_creation_datetime AS DATE)
这里有一个替代方案,也应该返回领带:
SELECT t.report_date, t.work_start, t.work_end, r1.id minid, r2.id maxid
FROM (
SELECT
CAST(reports.report_creation_datetime AS DATE) AS report_date,
MIN(CAST(reports.report_creation_datetime AS TIME)) AS work_start,
MAX(CAST(reports.report_creation_datetime AS TIME)) AS work_end
FROM reports
WHERE reports.report_creation_datetime >= '2016-02-01'
AND reports.report_creation_datetime < LAST_DAY('2016-02-01') + INTERVAL 1 DAY
GROUP BY CAST(reports.report_creation_datetime AS DATE)
) t
JOIN reports r1 ON t.report_date = CAST(r1.report_creation_datetime AS DATE) AND t.work_start = CAST(r1.report_creation_datetime AS TIME)
JOIN reports r2 ON t.report_date = CAST(r2.report_creation_datetime AS DATE) AND t.work_end = CAST(r2.report_creation_datetime AS TIME)
关于mysql - 从GROUP BY获取一天中最大和最小时间的ID行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35530821/