2016-05-15 54 views
0

我需要僅顯示上次登錄時間的用戶數據,數據爲 - 名稱,電子郵件,位置和日期時間。從SQL Server 2008數據庫獲取上次登錄時間

情景是用戶首次註冊他/她的自我,並將登錄日期時間插入到eventonline.participant表...現在爲了後續登錄同一用戶,我們只保存登錄時間到eventonline.logindatetime

下面是我使用的查詢,但它選擇所有用戶登錄數據而不是上次登錄日期時間。

select 
    a.firstname as Name, 
    a.Email as Email, 
    a.Address1 as Location, 
    a.MobileNo as Contact, 
    a.datetime, a.ID 
from 
    eventonline.participant a 
where 
    a.eventid = '" + Convert.ToString(ConfigurationManager.AppSettings["event_id"]) + "' 

union 

select 
    a.firstname as Name, 
    a.Email as Email, 
    a.Address1 as Location, 
    a.MobileNo as Contact, 
    b.datetime, b.Rid 
from 
    eventonline.participant a 
join 
    eventonline.logindatetime b on a.Id = b.Rid 
where 
    b.eventid = '" + Convert.ToString(ConfigurationManager.AppSettings["event_id"]) + "' 
order by 
    datetime desc 

回答

0

數據庫:eventonline ,表名:參與者,logindatetime

讓我們說你的參與者表包含以下數據: -

registration_id | user_phone | user_email | first_name | last_name | created_timestamp

1 | 5545555454 | [email protected] | tom |戴夫| 2016-03-05 21:33:55

2 | 5599992154 | [email protected] | riya |底部| 2016-03-05 15:33:55

3 | 5545876954 | [email protected] | greg |喬治| 2016年3月9日十二時32分55秒

而logindatetime表具有以下數據: -

ID | registration_id | ip_address | user_Agent | created_timestamp

1 | 2 | 10.2.3.101 | mozilla | 2016-03-05 15:54:11

2 | 3 | 10.0.5.99 |鉻| 2016-03-15 23:31:01

3 | 1 | 10.0.4.43 | safari | 2016-04-01 21:33:55

4 | 2 | 10.2.4.65 | mozilla | 2016-04-05 19:21:55

5 | 1 | 10.6.5.54 |鉻| 2016-04-11 19:12:15

現在,如果您想要檢索用戶數據以及對應於第5行的登錄數據,即logindatetime時間中的最新行,那麼以下的查詢將會起作用。

選擇a.registration_id,a.user_phone,a.user_email,a.first_name,a.last_name,b.ip_address,b.user_Agent,從參與者b.created_timestamp作爲JOIN logindatetime作爲b其中a.registration_id = b.registration_id order by b.created_timestamp desc limit 1;

結果

registration_id | user_phone | user_email | first_name | last_name ip_address | user_Agent | created_timestamp

1 | 5545555454 | [email protected] | tom |戴夫| 10.6.5。54 |鉻| 2016-04-11 19:12:15

+0

'SQL Server 2008'的限制1? – lad2025

+0

好吧,如果它的SQL服務器然後用戶SELECT TOP 1在查詢的開始,並從上面的查詢中刪除限制1部分。 – TECH007

+0

'從參與者作爲JOIN logindatetime作爲b where a.registration_id = b.registration_id' JOIN要求'ON'而不是'WHERE' – lad2025

0

這裏是我將如何去編寫查詢來做到這一點。 我在sql中使用了rank over函數來只抓取我想查看的數據分區中的最後或第一個值。

SELECT 
* 
FROM 
(
    select 
     -- Here is the magic that makes it work. 
     Rank() over (Partition BY a.Email order by a.datetime DESC) as Rank 
     a.firstname as Name, 
     a.Email as Email, 
     a.Address1 as Location, 
     a.MobileNo as Contact, 
     a.datetime, 
     a.ID 
    FROM 
    <YourFromCause> 
) 
-- naming the temp result set. 
tmp 
where 
    Rank = 1 
相關問題