【发布时间】:2018-02-28 08:50:53
【问题描述】:
我有一个带有 userId 和时间戳的表。对于每个用户,我想每天获取第一个和最后一个时间戳。我正在使用 SQL Server。 它的样子:
|User| Date |
----------------------------
| 1 | 2015-01-08 07:31:40 |
| 1 | 2015-01-08 18:35:40 |
| 1 | 2015-01-08 22:31:40 |
| 1 | 2015-01-09 05:35:40 |
| 1 | 2015-01-09 06:31:40 |
| 1 | 2015-01-09 07:35:40 |
| 1 | 2015-01-09 12:38:40 |
| 1 | 2015-01-09 23:38:40 |
| 2 | 2015-01-08 05:55:40 |
| 2 | 2015-01-08 10:48:40 |
| 2 | 2015-01-08 15:38:40 |
| 2 | 2015-01-08 21:50:40 |
| 2 | 2015-01-09 10:38:40 |
| 2 | 2015-01-09 14:33:40 |
| 2 | 2015-01-09 15:38:40 |
| 2 | 2015-01-09 17:38:40 |
| 2 | 2015-01-09 19:55:40 |
我需要的输出:
|User| Date |
----------------------------
| 1 | 2015-01-08 07:31:40 |
| 1 | 2015-01-08 22:31:40 |
| 1 | 2015-01-09 05:35:40 |
| 1 | 2015-01-09 23:38:40 |
| 2 | 2015-01-08 05:55:40 |
| 2 | 2015-01-08 21:50:40 |
| 2 | 2015-01-09 10:38:40 |
| 2 | 2015-01-09 19:55:40 |
到目前为止,它只适用于一个用户名:
SELECT
User,
Date,
min(Date) OVER(PARTITION BY Datepart(dy,Date)) as first,
max(Date) OVER(PARTITION BY Datepart(dy,Date)) as last
FROM
Tablename
WHERE
User = UserId
【问题讨论】:
-
查看 GROUP BY!
-
您使用的是哪个 dbms?
-
显示你到目前为止所做的事情......通过minimal reproducible example
标签: sql sql-server window-functions