我将如何查询以便显示每个用户最近的位置

时间:2017-05-08 16:03:52

标签: sql sql-server database

如何编写查询以显示每个用户的最新位置,类似于我的节目?我已经四处搜索但仍未能正确实施。

+----------+-----------+----------+-----------+-------------------------+
| Username | Firstname | Lastname | Location  |       DateandTime       |
+----------+-----------+----------+-----------+-------------------------+
| ms       | mark      | smith    | labs      | 2017-05-04 15:35:00.000 |
| jb       | james     | brown    | home      | 2017-05-04 18:55:00.000 |
| cj       | charlie   | jones    | uni       | 2017-05-04 18:56:00.000 |
| cj       | charlie   | jones    | home      | 2017-05-04 19:33:00.000 |
| ms       | mark      | smith    | shop      | 2017-05-05 15:40:00.000 |
| jb       | james     | brown    | somewhere | 2017-05-05 16:31:00.000 |
| ms       | mark      | smith    | work      | 2017-05-07 17:42:00.000 |
| ms       | mark      | smith    | market    | 2017-05-07 17:45:00.000 |
+----------+-----------+----------+-----------+-------------------------+

+----------+-----------+----------+-----------+-------------------------+
| Username | Firstname | Lastname | Location  |       DateandTime       |
+----------+-----------+----------+-----------+-------------------------+
| cj       | charlie   | jones    | home      | 2017-05-04 19:33:00.000 |
| jb       | james     | brown    | somewhere | 2017-05-05 16:31:00.000 |
| ms       | mark      | smith    | market    | 2017-05-07 17:45:00.000 |
+----------+-----------+----------+-----------+-------------------------+

2 个答案:

答案 0 :(得分:2)

您可以将窗口函数row_numbertop 1 with ties一起使用,以获取每个用户名的最新行。

select top 1 with ties *
from your_table
order by row_number() over (
        partition by username order by dateandtime desc
        );

答案 1 :(得分:2)

这应该有效:

;with cte_a as
(
    select distinct username, Firstname, Lastname from dbo.mytable
)
select a.username, a.Firstname, a.Lastname, q.[Location] [Last Location], q.DateAndTime
from cte_a a
outer apply
(
    select top 1 b.[Location], b.DateAndTime
    from dbo.myTable b 
    where b.Username = a.username
    order by DateAndTime desc
)q