簡體   English   中英

從SQL Server 2008數據庫獲取上次登錄時間

[英]Get last login time from SQL Server 2008 database

我只需要顯示上次登錄時間的用戶數據,數據為-名稱,電子郵件,位置和日期時間。

場景是用戶首次注冊自己,並且登錄日期時間插入到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

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

假設您的參與者表包含以下數據:

registration_id | user_phone | user_email | first_name | last_name | created_timestamp

1 | 5545555454 | test1@test.com | 湯姆| 戴夫 2016-03-05 21:33:55

2 | 5599992154 | test123@test.com | 里亞| 底部| 2016-03-05 15:33:55

3 | 5545876954 | test123@test.com | greg | 喬治| 2016-03-09 12: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 | 野生動物園| 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登錄日期時間,其中a.registration_id = b.registration_id按以下順序排序b.created_timestamp desc限制1;

結果

registration_id | user_phone | user_email | first_name | 姓氏ip_address | user_Agent | created_timestamp

1 | 5545555454 | test1@test.com | 湯姆| 戴夫 10.6.5.54 | 鍍鉻| 2016-04-11 19:12:15

這就是我編寫查詢的方式。 我在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM