SQL SELECT不同的查询

时间:2017-01-12 05:18:38

标签: mysql sql database

我有一个由no(auto increment)user(varchar)timein (timestamp)timeout (timestamp)组成的数据库表。

我想获得多个用户timein和timeout,我遇到了一些问题。

我能得到的最接近的是:

SELECT * FROM userdata WHERE no IN (SELECT MIN(no) FROM userdata GROUP BY user) 
UNION  
SELECT * FROM userdata WHERE no IN (SELECT MAX(no) FROM userdata GROUP BY user)

我得到的输出是:

[{"no":"1","user":"Alan","timein":"2017-01-12 12:31:19","timeout":"0000-00-00 00:00:00"},{"no":"3","user":"Alan","timein":"2017-01-12 12:34:00","timeout":"2017-01-12 12:34:00"}]

有没有什么方法可以获得不同的用户(因此输出不会重复)并在单行SQL中显示MIN(timein)和MAX(超时)?

期望的输出:{"用户":" Alan"," timein":" 12:31:19&# 34;,"超时":" 12:34:00"}

|---------------------|------------------|------------|------------|
|         no          |     user         |   timein   |   timeout  |
|---------------------|------------------|------------|------------|
|          1          |        Alan      |12:31:19    | 12:31:19   |
|---------------------|------------------|------------|------------|
|          2          |        Bill      |12:33:00    | 12:33:00   |
|---------------------|------------------|------------|----------- |
|          3          |        Alan      |12:34:00    | 12:34:00   |
|---------------------|------------------|------------|----------- |

2 个答案:

答案 0 :(得分:2)

SELECT user, MIN(timein), MAX(timeout)
FROM userdata
GROUP BY user

尝试使用group by语句,也许它可以帮助你。

答案 1 :(得分:0)

试试这个

SELECT ROW_NUMBER() OVER(ORDER BY user) AS no,user, MIN(timein), MAX(timeout)
FROM USER_TABLE GROUP BY user