Results 1 to 5 of 5

Thread: Group By

  1. #1
    Join Date
    Jan 2011
    Posts
    9

    Unanswered: Group By

    Is there a simple solution to this?

    SELECT COUNT(*) [Options] FROM [dbo].[Option] WHERE [QuestionID] = 15

    Result of the query above:

    Code:
    Options
    13
    SELECT OptionID, COUNT(*) [Options] FROM [dbo].[Answer] WHERE [QuestionID] = 15 GROUP BY [OptionID] ORDER BY [OptionID]

    Result of the query above:

    Code:
    OptionID	Options
    1		74
    2		12
    3		37
    4		2
    5		6
    6		37
    9		13
    10		9
    11		4
    12		2
    The problem is that there are 13 options to question #15 but no one has ever chosen the options 7, 8 or 13.

    The result I would like to see:

    Code:
    OptionID	Options
    1		74
    2		12
    3		37
    4		2
    5		6
    6		37
    7		0
    8		0
    9		13
    10		9
    11		4
    12		2
    13		0
    Is it possible to accomplish this by only editing the query? How?

  2. #2
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    What tells you that there are 13 options to question #15 ?

    -PatP
    In theory, theory and practice are identical. In practice, theory and practice are unrelated.

  3. #3
    Join Date
    Jan 2011
    Posts
    9
    Quote Originally Posted by Pat Phelan View Post
    What tells you that there are 13 options to question #15 ?

    -PatP
    If you scroll up you will notice that my first query tells me that:

    SELECT COUNT(*) [Options] FROM [dbo].[Option] WHERE [QuestionID] = 15

    Result of the query above:

    Code:
    Options
    13

  4. #4
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Code:
    SELECT OptionID
         , COUNT(ans.OptionID) AS [Options] 
      FROM [dbo].[Option] AS opt
    LEFT OUTER
      JOIN [dbo].[Answer] AS ans
        ON ans.QuestionID = opt.QuestionID
       AND ans.OptionID = opt.OptionID
     WHERE opt.QuestionID = 15 
    GROUP 
        BY opt.OptionID
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  5. #5
    Join Date
    Jan 2011
    Posts
    9
    Thank you very much!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •