SQL获取一行中每个日期的最小/最大时间

时间:2016-06-29 07:26:08

标签: mysql sql datetime max min

我需要一个帮助,我试着构建一个查询,它返回一行中每个日期的最大和最小时间,例如我有这个表:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>YOUR_COMPANY</groupId>
    <artifactId>YOUR_APP</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <project.java.version>1.8</project.java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <!-- Your dependencies -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${project.java.version}</source>
                    <target>${project.java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

结果应该是:

+---------+------------------------+----------+
|name     |Dates                   |Door      |
+---------+------------------------+----------+
|Maria    |2012-02-14 09:04:45.397 |Garage    |
|Maria    |2012-02-14 12:14:20.997 |Entrance |
|Maria    |2013-02-14 12:20:59.407 |Exit      |
|Maria    |2012-02-13 12:24:20.997 |garage    |
|Eli      |2013-02-13 10:30:59.407 |Entrance  |
|Eli      |2013-02-13 12:30:59.407 |Exit      |
+---------+------------------------+----------+

任何帮助都会感激:)

2 个答案:

答案 0 :(得分:0)

尝试此查询

    SELECT name, min(dates) as ENTRANCE, IF(max(dates)=MIN(dates),null,max(dates)) as 'Exit' 
from TEST3 GROUP BY name,day(dates);

答案 1 :(得分:0)

我不理解结果集的第一部分。

不应该如下吗?

+-------+---------------------+----------+
| name  | date                | door     |
+-------+---------------------+----------+
| Eli   | 2013-02-13 10:30:59 | Entrance |
| Maria | 2012-02-13 12:24:20 | Garage   |
| Maria | 2012-02-14 09:04:45 | Garage   |
+-------+---------------------+----------+