【问题标题】:time shift difference days mysql时移差异天mysql
【发布时间】:2019-02-24 12:56:13
【问题描述】:

我可以在同一天找到具有最小最大值的先进后出,但在不同的日子输出没有变化

表格属性

  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

【问题讨论】:

  • group by date(tgl),id更改为group by id
  • @RiggsFolly 不。不是这样的。
  • 谢谢@Strawberry,它受到了影响,但只有2个日期,如果超过2个日期怎么办?
  • 如果您有新问题,请提出新问题,并提供相应的数据集和所需的结果。

标签: mysql


【解决方案1】:

嗯,

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 中很好地处理,但最好在应用程序代码中处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多