Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi everybody,I'm struggling to acheive complicated SELECT statement. Could you please try to help me?I've 3 tables.Table 1: CategoriesCatIDCatDescriptionTable 2: TopicsTopicIDTopicDescriptionCatIDTable 3: SelectedTopicsSTIDTopicIDStatus (boolean)What I'd like to do is count the total selected topics which status is (True) per Category.The desired output need to be as follows:-----------------------Category | Total SelectedTopics-----------------------Category 1 | 2Category 2 | 3Category 3 | 0Category 4 | 1-------------------------I try to solve it but I end up with the following results:-----------------------Category | Total SelectedTopics-----------------------Category 1 | 2Category 2 | 3Category 4 | 1-------------------------Look at: Category 3 | 0 <<<< IS NOT DISPLAYEDCan you please help me to do it.
bklr
Master Smack Fu Yak Hacker
1693 Posts
Posted - 2010-04-02 : 07:36:06
try like this
SELECT c.catid,c.catdescription,s.cntFROM categories cLEFT JOIN (SELECT t.catid,COUNT(DISTINCT t.topicid) FROM topics t INNER JOIN selectedtopics AS s ON s.topicid = t.topicid AND s.status = 'TRUE' GROUP BY t.catid) AS s ON s.catid = c.catid
Vaio
Starting Member
2 Posts
Posted - 2010-04-02 : 12:32:41
Many thanks bklr, it is working 100%
bklr
Master Smack Fu Yak Hacker
1693 Posts
Posted - 2010-04-03 : 04:56:53
quote:Originally posted by Vaio Many thanks bklr, it is working 100%