这是我的查询
SELECT u.UserID , A.Username , A.Password , A.CreatedOn FROM dbo.tbl_User U INNER JOIN dbo.tbl_UserAuthDetail A ON A.UserID = U.UserID AND A.CreatedOn IN ( SELECT TOP 1 CreatedOn FROM dbo.tbl_UserAuthDetail WHERE A.UserID = U.UserID ORDER BY CreatedOn DESC )
它将返回
但是我桌上有这个
所以我期望会有额外的输入结果
如果我哪里出了问题,有人可以指导我吗?并且如果可能的话,请帮助我也将其转换为LINQ。
对不起,我的解释不好.. :)
TIA
您的子查询的where语句有些混乱:
FROM dbo.tbl_UserAuthDetail WHERE A.UserID = U.UserID
这两个A和U是子查询之外,因此这一条款不会在所有限制子查询。
A
U
尝试类似的东西:
FROM dbo.tbl_UserAuthDetail A2 WHERE A2.UserID = U.UserID
作为替代解决方案,SQL Server具有窗口功能:
select * from ( select row_number() over ( partition by u.UserID order by a.createdon desc) rn , * from dbo.tbl_user u join dbo.tbl_userauthdetail a on a.userid = u.userid ) as SubQueryAlias where rn = 1 -- Only latest authdetail per user
或者您可以使用cross apply:
cross apply
select * from dbo.tbl_user u cross apply ( select top 1 * from dbo.tbl_userauthdetail a where a.userid = u.userid order by a.createdon desc ) a