A
A
Abai Kerimov2016-11-28 01:15:36
SQL
Abai Kerimov, 2016-11-28 01:15:36

How can I create a table of counts?

Hello. I have an Answers table that stores scores for questions
Id------QuestionId--------Value
1-------1------------- ------5
2-------1-----4
3-------2----- --------------4
4-------2-----3
5----- --3-------------------5
I need to create a statistics table to calculate the number of fives, fours, triples, etc. for each question, that is, the table should look like this:
QuestionId------5-----4-----3
1-----------------1-----1-- ---0
2-----------------0-----1-----1
3-------------- ---1-----0-----0
How can I create a MSSQL query so that such a table is eventually created?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2016-11-28
@direwolf

select distinct 
  a.question_id,
  isnull(t5.val, 0) as '5',
  isnull(t4.val, 0) as '4',
  isnull(t3.val, 0) as '3',
  isnull(t2.val, 0) as '2',
  isnull(t1.val, 0) as '1'
from answers as a
left outer join (
  select question_id, count(*) as val from answers where value = 5 group by question_id
) as t5 on a.question_id = t5.question_id
left outer join (
  select question_id, count(*) as val from answers where value = 4 group by question_id
) as t4 on a.question_id = t4.question_id
left outer join (
  select question_id, count(*) as val from answers where value = 3 group by question_id
) as t3 on a.question_id = t3.question_id
left outer join (
  select question_id, count(*) as val from answers where value = 2 group by question_id
) as t2 on a.question_id = t2.question_id
left outer join (
  select question_id, count(*) as val from answers where value = 1 group by question_id
) as t1 on a.question_id = t1.question_id;

M
Melkij, 2016-11-28
@melkij

select QuestionId, 
sum(case when Value = 5 then 1 else 0 end) as '5'
sum(case when Value = 4 then 1 else 0 end) as '4'
sum(case when Value = 3 then 1 else 0 end) as '3'
from tablename
group by QuestionId

Perhaps your DBMS is able to perform the pivot operation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question