views:

106

answers:

4

I have the following SQL query and so far it works the way it should and gets the top 40 tag ids that I have stored in the tagmap table.

SELECT TOP 40
tbrm_TagMap.TagID,
Count(*)
FROM tbrm_TagMap
GROUP BY tbrm_TagMap.TagID
ORDER BY COUNT(tbrm_TagMap.TagID) DESC

I also want to join to the Tags table which contains the actual name of each TagID. Each attempt I make comes back with an error. How can I achieve this? I am using SQL 2008.

+5  A: 
SELECT  *
FROM    (
        SELECT  TOP 40 
                tbrm_TagMap.TagID, COUNT(*) AS cnt
        FROM    tbrm_TagMap
        GROUP BY
                tbrm_TagMap.TagID
        ORDER BY
                COUNT(*) DESC
        ) q
JOIN    Tags
ON      Tags.id = q.TagID
ORDER BY
        cnt DESC
Quassnoi
what is the benefit of joining later instead of using a single join?
Raj More
@Raj: It may be faster, depending on the result set.
Eric
`@Raj`: to avoid grouping by all fields in `Tags`.
Quassnoi
+1  A: 

My guess is that when you were joining tags, you weren't including it in the group by clause, which will always through an error in SQL Server. Every column not aggregated but returned needs to be in the group by.

Try something like this:

SELECT TOP 40
    tbrm_TagMap.TagID,
    t.Tag,
    Count(*)
FROM 
    tbrm_TagMap
    INNER JOIN tags t ON
        tbrm_TagMap.TagID = t.TagID
GROUP BY 
    tbrm_TagMap.TagID, 
    t.Tag
ORDER BY 3 DESC
Eric
@Eric: Why the ORDER BY 3 instead of Order by COUNT (*)? Doesn't that cause a problem when you add columns to the query?
Raj More
`order by count(*)` may kick off the count again. Best just to order by the already calculated column. And yes, it does screw it up if you add columns. The better solution is to name `count` as something, then order by that.
Eric
+1  A: 
SELECT TOP 40
tbrm_TagMap.TagID, Tags.TagName Count(*)
FROM tbrm_TagMap INNER JOIN Tags ON tbrm_TagMap.TagID = Tags.TagID
GROUP BY tbrm_TagMap.TagID, Tags.TagName
ORDER BY COUNT(tbrm_TagMap.TagID) DESC
Paul McLean
This will break. `Tags.TagName` needs to go in the `group by` clause in SQL Server.
Eric
Good catch, thanks.
Paul McLean
+1  A: 

Try this..

SELECT top 40 tags.TagDescription, tbrm_TagMap.TagID, Count(*)
FROM tbrm_TagMap
    INNER JOIN Tags 
       ON TagMap.TagID = Tags.TagId
GROUP BY tags.TagDescription, tbrm_TagMap.TagID
ORDER BY COUNT(tbrm_TagMap.TagID) DESC
Raj More