Query
根據 3 列選擇每天最近的記錄
我有一個看起來像這樣的表:
CREATE TABLE tbl_AppUsage( ID int IDENTITY(1,1) NOT NULL, UserName nchar(250) NULL, UPN nchar(250) NULL, AppDisplayName nchar(250) NULL, AppId nchar(250) NULL, CreatedDateTime nchar(250) NULL);
INSERT INTO tbl_AppUsage (UserName, UPN, AppDisplayName, AppId, CreatedDateTime) VALUES ('aaa', 'aaa@mail.com', 'Adobe DC', '1234fdr234', '07/10/2020 08:39:14'), ('aaa', 'aaa@mail.com', 'Adobe DC', '1234fdr234', '07/10/2020 08:51:14'), ('aaa', 'aaa@mail.com', 'Adobe DC', '1234fdr234', '07/10/2020 09:39:14'), ('aaa', 'aaa@mail.com', 'Adobe DC', '1234fdr234', '07/11/2020 09:39:14'), ('bbb', 'bbb@mail.com', 'Adobe DC', '1234fdr234', '07/10/2020 08:39:14'), ('bbb', 'bbb@mail.com', 'Adobe DC', '1234fdr234', '07/10/2020 09:39:14'), ('bbb', 'bbb@mail.com', 'Adobe DC', '1234fdr234', '07/11/2020 10:39:14'), ('bbb', 'bbb@mail.com', 'Adobe DC', '1234fdr234', '07/11/2020 10:51:14') ;
我想創建一個查詢,返回每個使用者每天的最新記錄
我嘗試了以下方法:
SELECT ID ,UserName ,UPN ,AppDisplayName ,AppId ,CreatedDateTime FROM tbl_AppUsage T1 WHERE CreatedDateTime=( SELECT MAX(CreatedDateTime) FROM tbl_AppUsage WHERE UserName = T1.UserName AND AppId = T1.AppId) GROUP BY UserName
沒有成功,老實說,我有點卡住了。我將查詢的表有 200 000 多條記錄,我使用 MS SQL 2017 作為 DBMS。我不確定在考慮性能的情況下獲取數據的最佳方法是什麼。
注意:我知道列(如 CreatedDateTme)可以是其他類型,但在這種情況下,它必須是 nchar。
實現此目的的一種方法是使用,
ROW_NUMBER
因為您需要 每個使用者每天記錄,我在
PARTITION
:a.UserName, CAST(CreatedDateTime as DATE)
中添加了最新記錄,我添加了
ORDER BY CAST(CreatedDateTime as DATETIME) DESC
SELECT src.ID , src.UserName, src.UPN, src.AppDisplayName, src.AppId, src.CreatedDateTime FROM ( SELECT ID , UserName, UPN, AppDisplayName, AppId, CreatedDateTime, ROW_NUMBER()OVER(PARTITION BY a.UserName, CAST(CreatedDateTime as DATE) ORDER BY CAST(CreatedDateTime as DATETIME) DESC)as rn FROM dbo.tbl_AppUsage as a )as src WHERE src.rn = 1
輸出:
ID UserName UPN AppDisplayName AppId CreatedDateTime ----------- ----------- ---------------- --------------- ------------- ------------------- 3 aaa aaa@mail.com Adobe DC 1234fdr234 07/10/2020 09:39:14 4 aaa aaa@mail.com Adobe DC 1234fdr234 07/11/2020 09:39:14 6 bbb bbb@mail.com Adobe DC 1234fdr234 07/10/2020 09:39:14 8 bbb bbb@mail.com Adobe DC 1234fdr234 07/11/2020 10:51:14
根據您的查詢,相同的輸出
SELECT ID ,UserName ,UPN ,AppDisplayName ,AppId ,CreatedDateTime FROM tbl_AppUsage as T1 WHERE CreatedDateTime=( SELECT MAX(CreatedDateTime) FROM tbl_AppUsage as T2 WHERE T2.UserName = T1.UserName --AND AppId = T1.AppId AND CAST(T1.CreatedDateTime AS DATE) =CAST(T2.CreatedDateTime AS DATE) ) --GROUP BY UserName