user441222
user441222

Reputation: 2001

About SQL SERVER LEFT JOIN and Group by

I have two tables,Blog table has a FK BlogTagID column point to BlogTag table:

Blog table:

BlogID BlogTagID BlogTitle
  1       2        test1
  2       1        test2
  3       2        test3

BlogTag table:

BlogTagID BlogTagName
  1        JAVA        
  2        .NET        
  3        PHP       

I would like to get the result:

BlogTagName  count
   JAVA         1
   .NET         2
   PHP          0

How to get this?Thank you very much!

Upvotes: 0

Views: 44

Answers (2)

Viji
Viji

Reputation: 2629

try this code

select BlogTagName, count(blogid)
from BlogTag bt
left join Blog b on b.blogtagid = bt.BlogTagID
group by BlogTagName

SQL FIDDLE : http://sqlfiddle.com/#!3/356c5/8/0

Upvotes: 2

Heshitha Hettihewa
Heshitha Hettihewa

Reputation: 368

You can try this also

SELECT BlogTagName,COUNT(BlogTagID) FROM Blog b JOIN BlogTagID bt WHERE b.BlogTagID=bt.BlogTagID GROUP BY BlogTagID;

Upvotes: 1

Related Questions