SQL:选择子查询的最小值并对

时间:2015-10-14 11:11:17

标签: mysql

我有一些在MySQL DB中签入和签出人员的记录:

SELECT * FROM db

结果:

-----------------------------------------------------------------------
ID            Name       Lastname           in                out
1             James      Bond         20151014090000     20151014103000
2             James      Bond         20151014110000     20151014123000
3             James      Bond         20151014130000     20151014143000
4             James      Bond         20151014150000     20151014163000
5             James      Bond         20151014170000     20151014183000
6             James      Bond         20151014190000     20151014203000
7             Jason      Bourne       20151014090000     20151014103000
8             Jason      Bourne       20151014110000     20151014123000
9             Jason      Bourne       20151014130000     20151014143000
10            Jason      Bourne       20151014150000     20151014163000
11            Jason      Bourne       20151014170000     20151014183000
12            Jason      Bourne       20151014190000     20151014203000
13            Jack       Bauer        20151014090000     20151014103000
14            Jack       Bauer        20151014110000     20151014123000
15            Jack       Bauer        20151014130000     20151014143000
16            Jack       Bauer        20151014150000     20151014163000
17            Jack       Bauer        20151014170000     20151014183000
18            Max        Payne        20151014090000     20151014103000
19            Max        Payne        20151014110000     20151014123000
20            Max        Payne        20151014130000     20151014143000
21            Max        Payne        20151014150000     20151014163000
22            Max        Payne        20151014170000     20151014183000

我想得到最接近当前日期的日期,即条目,考虑到它们在(IN)内。

我正在使用,与MySQL中的当前日期进行比较:

date_format(now(), '%Y%m%d%H%i%S')

假设是20151014133000

我希望查询的内容是:

3             James      Bond         20151014130000     20151014143000
9             Jason      Bourne       20151014130000     20151014143000
15            Jack       Bauer        20151014130000     20151014143000
20            Max        Payne        20151014130000     20151014143000

提前问候并非常感谢你!

[EDIT1] 进出是int的 我将它与该格式的实际时间进行比较,因为操作: date_actual - in_value = time_lapsed 例如:

20151014133000 - 20151014090000 = 43000

如果我得到time_lapsed的最小值,我会得到最接近date_actual的日期,然后我将在DB上搜索按姓名和姓氏分组的日期分组。

1 个答案:

答案 0 :(得分:1)

如果我理解你需要:

SELECT DISTINCT `Name`, `Lastname`, MAX(IN) FROM DB