SQL Server表在GROUP查询中添加上次访问的ID

时间:2014-12-16 13:12:39

标签: sql sql-server select group-by greatest-n-per-group

我有一个SQL Server数据库表,其中包含用户列表及其上次访问。我想提取所有访问者的上次访问列表以及表ID。

让我通过举个例子来解释一下。 这是一个简化版本

Visits
| id | visitor | last_visit |
|----|---------|------------|
|   1|     ABC | 2014-04-06 |
|   2|     DEF | 2014-04-06 |
|   3|     GHI | 2014-04-07 |
|   4|     DEF | 2014-04-07 |
|   5|     ABC | 2014-04-08 |
|   6|     JKL | 2014-04-10 |
|   7|     DEF | 2014-04-12 |

这就是我想要获得的:

| id | visitor | last_visit |
|----|---------|------------|
|   3|     GHI | 2014-04-07 |
|   5|     ABC | 2014-04-08 |
|   6|     JKL | 2014-04-10 |
|   7|     DEF | 2014-04-12 |

我设法通过做一个简单的GROUP来获得没有id列的结果:

SELECT visitor, MAX(last_visit) FROM visits GROUP BY visitor

但是我不知道如何添加id,这对我来说是最基本的。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT a.id, a.visitor, a.last_visit
FROM visits a 
INNER JOIN (SELECT visitor, MAX(last_visit) last_visit 
            FROM visits 
            GROUP BY visitor
          ) AS b on a.visitor = b .visitor and a.last_visit = b.last_visit;

SELECT a.id, a.visitor, a.last_visit 
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY a.visitor ORDER BY a.last_visit DESC) AS RowNo, 
             a.id, a.visitor, a.last_visit
      FROM visits a
    ) AS a 
WHERE RowNo = 1;

答案 1 :(得分:1)

使用row_number()代替group by

select v.*
from (select v.*, row_number() over (partition by visitor order by last_visit desc) as seqnum
      from visits v
     ) v
where seqnum = 1;