我正在尝试构建一个具有线程和帖子的系统。我正在尝试获取最受欢迎的线程(用户可以单击“喜欢”按钮以使其更受欢迎)并且拥有大多数帖子。问题是按大多数帖子排序结果......然后按喜欢的帖子排序。
所以例如,如果我有一个帖子有300个帖子,200个喜欢..而另一个帖子有300个喜欢和201个喜欢..我想要第二个帖子被选中..
表结构简而言之:
topic:
--------
topic_id
liked
comment:
-------
comment_id
topic_id
到目前为止,这是我的存储过程:
dbo.Trends
AS
SELECT TOP 1 title, COUNT(com.topic_id), COUNT(topc.user_id_liked)
FROM comment AS com
INNER JOIN topic AS topc ON com.topic_id=topc.topic_id
GROUP BY com.topic_id, topc.user_id_liked,title
ORDER BY COUNT(com.topic_id), COUNT(topc.user_id_liked) DESC
我不确定我是对的,还是必须控制流逻辑。我在order语句中的topic like列之前放置了topic_id来自topic表。希望topic_id的选择/排序将占优势。
更新:查询已更新。
答案 0 :(得分:2)
我真的不知道你想要什么。但也许这会有所帮助:
;WITH CTE
AS
(
SELECT
COUNT(com.topic_id) OVER(PARTITION BY topc.liked) AS topicCount,
COUNT(com.liked) OVER(PARTITION BY topc.topic_id) AS likedCount,
title
FROM
commnet AS com
INNER JOIN topic AS topc
ON com.topic_id=topc.topic_id
)
SELECT TOP 1
CTE.title,
CTE.topicCount,
CTE.likedCount
FROM
CTE
ORDER BY
topicCount,
likedCount
修改强>
GROUP BY
和PARTITION BY
之间的区别在于PARTITION BY
是内联GROUP BY
,因此这不会影响行数。我喜欢在CTE中使用它,这是一个内联视图。使其更清晰,并将您想要执行的不同步骤分开。如果您删除TOP 1
,您将会看到我的意思。