时移时差天数mysql

时间:2019-02-24 12:56:14

标签: mysql

我可以在同一天找到min max的先进先出,但在差值日输出没有变化

桌位

  id     tgl                  
| 111 | 2019-02-24 07:30:00  |
| 111 | 2019-02-24 16:31:00  |
| 222 | 2019-02-24 17:59:00  |
| 222 | 2019-02-25 07:31:00  |
| 333 | 2019-02-24 07:30:00  |
| 333 | 2019-02-24 18:00:00  |

我的查询

select id, min(date(tgl)) as date_in, max(date(tgl)) as date_out, 
        min(time(tgl)) as jam_in, max(time(tgl)) as jam_out 
from Att 
group by date(tgl),id

导致我的查询

  id     tgl_in       tgl_out     jam_in    jam_out 
| 111 | 2019-02-24 | 07:30:00 | 2019-02-24 | 16:31:00 |
| 222 | 2019-02-24 | 17:59:00 | 2019-02-24 | 17:59:00 |
| 222 | 2019-02-25 | 07:31:00 | 2019-02-25 | 07:31:00 |
| 333 | 2019-02-24 | 07:30:00 | 2019-02-24 | 18:00:00 | 

所需的输出

 id     tgl_in       tgl_out    jam_in    jam_out 
| 111| 2019-02-24 | 2019-02-24 |07:30:00 | 16:31:00 | 
| 222| 2019-02-24 | 2019-02-25 |17:59:00 | 07:31:00 | 
| 333| 2019-02-24 | 2019-02-24 |07:30:00 | 18:00:00 |

我将查询更改为按ID分组

select id, min(date(tgl)) as date_in, max(date(tgl)) as date_out, min(time(tgl)) as jam_in, max(time(tgl)) as jam_out from Att group by id

但是结果时间jam_in和jam_out id 222不正确

id  date_in     date_out    jam_in      jam_out
111 2019-02-24  2019-02-24  07:30:00    16:31:00
222 2019-02-24  2019-02-25  07:31:00    17:59:00
333 2019-02-24  2019-02-24  07:30:00    18:00:00

1 个答案:

答案 0 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL
,tgl DATETIME
,PRIMARY KEY(id,tgl)
);

INSERT INTO my_table VALUES
(111,'2019-02-24 07:30:00'),
(111,'2019-02-24 16:31:00'),
(222,'2019-02-24 17:59:00'),
(222,'2019-02-25 07:31:00'),
(333,'2019-02-24 07:30:00'),
(333,'2019-02-24 18:00:00');

SELECT id, MIN(tgl) x, MAX(tgl) y FROM my_table GROUP BY id;
+-----+---------------------+---------------------+
| id  | x                   | y                   |
+-----+---------------------+---------------------+
| 111 | 2019-02-24 07:30:00 | 2019-02-24 16:31:00 |
| 222 | 2019-02-24 17:59:00 | 2019-02-25 07:31:00 |
| 333 | 2019-02-24 07:30:00 | 2019-02-24 18:00:00 |
+-----+---------------------+---------------------+

此问题的其余部分是格式化方面的一个练习,尽管可以很好地在SQL中很好地处理它,但最好在应用程序代码中对其进行处理。