我有大约7条记录,其中两条记录具有相同的用户但具有不同的MailLevel& SentDate状态,所以我只想获得该特定用户的最新记录。任何人都可以帮助我如何执行Sql查询
请查看下面的图片以便清楚了解
答案 0 :(得分:1)
如果您只想使用此特定用户的最新记录,则可以使用:
CREATE PROCEDURE SelectLatestRecored
@UserId int
AS
SELECT TOP 1 [Col1], [Col2] ,[Col3], [SendDate], [MailLevel]
FROM [YourTable]
ORDER BY [SentDate] DESC
WHERE [UserId] = @UserId
GO
如果您想要每个用户的最新记录:
CREATE PROCEDURE SelectLatestRecoreds
AS
SELECT
ROW_NUMBER() OVER (PARTITION BY [UserId] ORDER BY [SendDate] DESC) AS [RowNum],
[Col1], [Col2] ,[Col3], [SendDate], [MailLevel]
FROM [YourTable]
WHERE [RowNum] = 1
GO
答案 1 :(得分:1)
子选择在主选择
上添加行号列和where子句的表SELECT *
FROM (
SELECT MyTable.*, ROW_NUMBER() OVER (Partition BY UserId ORDER BY MailLevel DESC, SentDate DESC) AS R
FROM MyTable ) AS T
WHERE T.R=1
答案 2 :(得分:-2)
根据我对具有2次不同邮件级别和发送日期的条目的用户记录的理解,它将选择最近的记录以及其他记录。
select *
from
(
SELECT
ROW_NUMBER() OVER (PARTITION BY [creatorName] ORDER BY [SendDate] DESC)
AS [RowNum],
*
FROM [YourTable]
)base
WHERE [RowNum] = 1