选择列的最大值时的JOIN表

时间:2014-02-09 20:04:31

标签: sql sql-server

我有以下表结构,可以成功获取每个CommentID的表的最大列值。但我希望将tbCommenttbCommentBreadcrumb加在一起,其中CommentID是关键。

tbComment

CommentID     IsLocked
1             0      
2             0
3             1
4             0
5             1

tbCommentBreadcrumb

CommentStatusID  CommentID   StatusTypeID
105              1           1                
106              1           4                
107              2           1                
108              3           1               
109              3           4
110              4           1 
112              5           1
112              5           4

这就是我的工作:

SELECT *
FROM
(
   SELECT
     *,
     ROW_NUMBER() OVER (PARTITION BY CommentID ORDER BY CreateDateTime desc) as rn
   FROM
     tbCommentBreadCrumb
   WHERE 
     CommentStatusTypeID = 4
     AND CreateDateTime <= {ts '2014-02-09 09:44:57'}
) t
WHERE
   t.rn = 1
ORDER BY 
   CommentStatusID DESC

这会返回超过一百条记录,我希望通过仅获取上述查询为真的记录以及表CommentID中的每个tbComment都被锁定来进一步细化查询。基本上不确定在哪里加入tbComment并放置AND tbComment.CommentIsLocked = 1

2 个答案:

答案 0 :(得分:2)

你非常接近: - )

SELECT t.*
FROM
(
   SELECT
     *,
     ROW_NUMBER() OVER (PARTITION BY CommentID ORDER BY CreateDateTime desc) as rn
   FROM
     tbCommentBreadCrumb
     WHERE CommentStatusTypeID = 4
            AND    CreateDateTime <= {ts '2014-02-09 09:44:57'}
) t
JOIN tbComment c ON t.CommentID = c.CommentID
WHERE
   t.rn = 1
AND c.CommentIsLocked = 1
ORDER BY CommentStatusID DESC

答案 1 :(得分:1)

;With CTE
AS
(
   SELECT *,
       ROW_NUMBER() OVER (PARTITION BY CommentID ORDER BY CreateDateTime desc) as rn
   FROM  tbCommentBreadCrumb
   WHERE CommentStatusTypeID = 4
   AND   CreateDateTime <= {ts '2014-02-09 09:44:57'}
) 
SELECT * 
FROM CTE C INNER JOIN tbComment TC
ON C.CommentID = TC.CommentID   
WHERE  C.rn = 1
ORDER BY C.CommentStatusID DESC