SQL count on a field which is a code

I have a table

ANSWERS 
   qId
   toggle_value

which records an HTML radio button value {Yes, N/A, No, Resolved}

Now I want to count and summarize how many yeses, nos, nas and resolved grouped by question Id.

For simplicity I started to build each individual query.

SELECT qId, count(*) as yes_qty FROM ANSWERS WHERE TOGGLE_VALUE='Yes' GROUP BY qId;
SELECT qId, count(*) as na_qty FROM ANSWERS WHERE TOGGLE_VALUE='NA' GROUP BY qId;
SELECT qId, count(*) as no_qty FROM ANSWERS WHERE TOGGLE_VALUE='No' GROUP BY qId;
SELECT qId, count(*) as resolved_qty FROM ANSWERS WHERE TOGGLE_VALUE='Resolved' GROUP BY qId;

But I really want it in one query so I can iterate over the list and display something like this ( aggregating 14 Checklists with 3 questions)

Q      Yes      No     NA     Resolved
1       4       10     0        10
2      14        0     0         0
3       7        0     7         0

I don't actually use strings for the toggle value but numbers 1=yes, 2=NA, etc... and was wondering if a better table design would have been

ANSWERS 
   qId
   yes_value
   no_value
   na_value
   resolved_value

I'd have to refactor a lot of other things if I changed the table deisgn so I was hoping to get a single query working.

Answers


SELECT qId,
       SUM(CASE WHEN TOGGLE_VALUE='Yes' THEN 1 ELSE 0 END) AS YesQty,
       SUM(CASE WHEN TOGGLE_VALUE='No' THEN 1 ELSE 0 END) AS NoQty,
       SUM(CASE WHEN TOGGLE_VALUE='NA' THEN 1 ELSE 0 END) AS NAQty,
       SUM(CASE WHEN TOGGLE_VALUE='Resolved' THEN 1 ELSE 0 END) AS ResolvedQty
  FROM ANSWERS 
 GROUP BY qId

Need Your Help

Get field name of JSON

php json

i have a JSON with list of servers:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.