Anthony Morack
Anthony Morack

Reputation: 29

Query returning users, first record and last record

I am attempting to write a query showing our unique users, the date of their first recorded entry in the system and the date of their last recorded entry. These are split between two tables: Users table and log table.

Users:

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

Log:

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

This is the desired result of the query I am attempting to write:

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

So far I have the first two columns, however I cannot figure out the First and Last date columns, below is my query so far:

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

I am using SQL Server 2008. I would love some help.

Upvotes: 1

Views: 766

Answers (3)

Just get the min and max of the date for each record.

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 

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1270401

You simply need a 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      

Upvotes: 0

Taryn
Taryn

Reputation: 247810

All you need is to apply an aggregate function to get the min and max dates and then 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

See SQL Fiddle with Demo

Upvotes: 1

Related Questions