I have the below table structure that is successfully getting the max column value of a table for each CommentID
. But I want to JOIN the table tbComment
with tbCommentBreadcrumb
where CommentID
is the key.
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
Here's what I have working:
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
This returns over a hundred records and I want to further refine the query by only getting the records where the above query is true but also that each of the CommentID
in the table tbComment
is locked. Basically not sure where to JOIN tbComment
and put the AND tbComment.CommentIsLocked = 1
You are quite close :-)
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
;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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.