1

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

用户:

| 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    |

到目前为止,我有前两列,但是我无法弄清楚第一个和最后一个日期列,下面是我到目前为止的查询:

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

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

4

3 回答 3

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 
于 2013-02-06T20:47:19.937 回答
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

于 2013-02-06T20:48:51.583 回答
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      
于 2013-02-06T20:49:12.810 回答