选择列的最大值时加入表
Posted
技术标签:
【中文标题】选择列的最大值时加入表【英文标题】:JOIN table when selecting a max value of columns 【发布时间】:2014-02-09 20:04:31 【问题描述】:我有下面的表结构,它成功地获取了每个CommentID
的表的最大列值。但我想用tbCommentBreadcrumb
加入表tbComment
,其中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
这将返回一百多条记录,我想通过仅获取上述查询为真但表tbComment
中的每个CommentID
被锁定的记录来进一步细化查询。基本上不知道在哪里加入tbComment
并把AND tbComment.CommentIsLocked = 1
放在哪里
【问题讨论】:
【参考方案1】:你很亲密:-)
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
【讨论】:
【参考方案2】:;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
【讨论】:
以上是关于选择列的最大值时加入表的主要内容,如果未能解决你的问题,请参考以下文章