2013-02-06 155 views
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.我想要一些幫助。

回答

1

剛剛獲得min和日期爲每個記錄的max

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

完美的答案。非常感謝。 –

+1

不需要與羣組區分,但它仍然有效。 – gmm

+0

@gmm - 是的,你說的對,我的部分已經過時了 – LittleBobbyTables

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

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  
相關問題