查询返回用户,第一条记录和最后一条记录

时间:2013-02-06 20:44:48

标签: sql sql-server sql-server-2008

我正在尝试编写一个查询,显示我们的唯一用户,他们在系统中首次记录的条目的日期以及他们最后记录的条目的日期。它们分为两个表:Users表和日志表。

用户:

| Userid | Username    |
|--------|-------------|
|20      | Tom Smith   |
|21      | Jim Jones   |
|22      | Sandy Brown |

日志:

| Logid | UserID  | Date       | Value        |
--------|---------|------------|--------------|
| 1     | 21      | 01/03/2013 | Login        |
| 2     | 22      | 01/04/2013 | Login        |
| 3     | 21      | 01/05/2013 | Edit         |
| 4     | 20      | 01/06/2013 | Login        |
| 5     | 20      | 01/07/2013 | Search       |
| 6     | 22      | 01/08/2013 | Login        |
| 7     | 21      | 01/09/2013 | Close        |
| 8     | 21      | 01/11/2013 | Login        |
| 9     | 20      | 01/12/2013 | Edit         |
| 10    | 22      | 01/13/2013 | Search       |

这是我试图编写的查询的理想结果:

|Userid | UserName    | First Log Date | Last Log Date |
|-------|-------------|----------------|---------------|
| 20    | Tom Smith   | 01/06/2013     | 01/12/2013    |
| 21    | Jim Jones   | 01/03/2013     | 01/11/2013    |
| 22    | Sandy Brown | 01/04/2013     | 01/13/2013    |

到目前为止,我有前两列,但是我无法弄清楚First和Last日期列,下面是我目前的查询:

select 
    distinct(u.userid1) as 'Userid',
    u.username as 'UserName'
from 
    users u,
    log l
where
    u.userid = l.userid

我正在使用SQL Server 2008.我希望得到一些帮助。

3 个答案:

答案 0 :(得分:1)

只需获取每条记录的日期minmax

select 
    u.userid as [Userid],
    u.username as [UserName],
    min([Date]) as [First Log Date],
    max([Date]) as [Last Log Date]
from users u 
inner join log l on u.userid = l.userid
group by u.userid, u.username 

答案 1 :(得分:1)

您只需要应用聚合函数来获取minmax日期,然后group by u.userid, u.username

select u.userid as 'Userid',
  u.username as 'UserName',
  min(l.date) FirstDate,
  max(l.date) lastDate
from users u
inner join log l
  on u.userid = l.userid
group by u.userid, u.username

请参阅SQL Fiddle with Demo

答案 2 :(得分:0)

您只需要一个group by

select u.userid, u.username,
       MIN(date) as FirstLogDate, MAX(date) as MaxLogDate
from users u join
     log l
      on u.userid = l.userid
group by u.userid, u.username