I am trying to build a system, which has threads and posts. I am trying to fetch a thread that is the most popular (the user can click “like” button to make it more popular) and has most posts. The problem is to order the results by most posts..and then by liked posts.
So for example, if I have a thread with 300 posts, and 200 likes.. while another thread has got 300 likes and 201 likes..I want the second post to be selected..
Table structure in a nutshell:
topic:
--------
topic_id
liked
comment:
-------
comment_id
topic_id
Here is my stored procedure so far:
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
I am not sure if I am right, or will I have to result to control flow logic. I placed the topic_id from the topic table before topic liked column in the order statement..hoping the selecting/ordering of the topic_id will take precendence.
UPDATED: query updated.
I don’t really know that you want. But maybe this will help:
EDIT
The differences between the
GROUP BYandPARTITION BYis thatPARTITION BYis an inlineGROUP BYso this will not affect the number of rows. I like to use that in a CTE that is a inline view. Makes it clearer and you separate the different steps you want to do. If you remove theTOP 1you will see what I mean.