我有一个临时表,我正在一个包含我的用户信息的sproc中创建。我需要将此表连接到另一个具有该特定用户的SEVERAL行的表,但我只想从“many”表中返回一个结果。
类似这样的事情
SELECT u.firstname, u.lastname
FROM #users AS u
INNER JOIN OtherTable AS ot on u.userid = (top 1 ot.userid)
很明显,这不会起作用,但这是我想要做的事情的要点有两个原因,一个我只想要返回一行(按日期字段降序)和两个用于最佳目的。查询必须扫描当前的几千行..
答案 0 :(得分:3)
SELECT
u.firstname, u.lastname, t.*
FROM
#users AS u
CROSS APPLY
(SELECT TOP 1 *
FROM OtherTable AS ot
WHERE u.userid = ot.userid
ORDER BY something) t
答案 1 :(得分:2)
使用ROW_NUMBER()函数按日期时间排序行,然后按row_num = 1过滤
;WITH otNewest
AS
(
SELECT *
FROM othertable
WHERE ROW_NUM() OVER(partition by userid order by datetime DESC) = 1
)
SELECT u.firstname, u.lastname, o.*
FROM #users U
INNER JOIN otNewest O
ON U.userid = O.userid
答案 2 :(得分:0)
所以,如果你加入但没有从OtherTable
返回任何列,那么你只对检查存在感兴趣吗?
SELECT u.firstname, u.lastname
FROM #users AS u
WHERE EXISTS(SELECT 1
FROM OtherTable ot
WHERE u.userid = ot.userid)