Answer Label Answer Count
Strongly Agree 10
Agree 7
Neutral 12
Disagree 19
Strong Disagree 9
For every Answer Label, I need the table to create a new row that displays the label and count so it looks just like the above. The problem occurs when the dataset does not include one or more Answer Labels because there are no counts associated to them. I still need to see all Answer Labels ... but simply set the count = 0 if it is not found in the dataset.
So working with a resultset like this:
Strongly Agree 10
Neutral 12
My table data region needs to look like such:
Strongly Agree 10
Agree 0
Neutral 12
Disagree 0
Strong Disagree 0
Is there a good way to do this?
Thanks - WaydeIf your dataset doesn't contain the rows it makes no sense to produce them afterwards..
If you have two tables, persons and answers you could left/right join them:
SELECT person.Name, count(answers.answer) as AnswerCount
FROM person LEFT JOIN answers ON person.ID = answers.personID
group by person.ID;
This statement means:
Take ALL persons from person and connect it with found answers of the answer-table, so you always get all persons and blank or "0" values for the answers.. If AnswerCount is empty you could use isnull(count(answers.answer),"0")
|||
Another approach would be:
-- Assume schema:
-- Table: AnswerTypes
-- ID (PK)
-- Label
-- Table: Answers
-- AnswerTypeId (FK)
--
select label, IsNull(a.CountAnswers, 0) as votes from AnswerTypes
left outer join
(
select AnswerTypeId, count(*) as CountAnswers from Answers
group by AnswerTypeId
) a on AnswerTypes.ID = a.AnswerTypeID
No comments:
Post a Comment