Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

T-Sql ordering results with count() by priority

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.

Upvotes: 0

Views: 364

Answers (1)

Arion
Arion

Reputation: 31239

I don't really know that you want. But maybe this will help:

;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

EDIT

The differences between the GROUP BY and PARTITION BY is that PARTITION BY is an inline GROUP BY so 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 the TOP 1 you will see what I mean.

Upvotes: 2

Related Questions