如何计算count函数中的多个值

时间:2015-03-28 18:27:46

标签: sql asp.net count

id q1     q2     q3     q4      q5
-----------------------------------
 1 v.good good   fair good    fair
-----------------------------------
 2 good   v.good fair good    fair

我想要这样回答

----------------------
status q1 q2 q3 q4 q5
----------------------
v.good  4  3  2  4  3
----------------------
good    4  5  6  7  8
----------------------
fair    5  7  6  3  9
----------------------

任何人都可以帮助我解决这个问题我感到困惑 提前谢谢

3 个答案:

答案 0 :(得分:0)

我假设您的样本数据不完整,因为您的预期输出似乎与您提供的计数有很大关系。

如果是这种情况,我想解释你想要的是:

select 'v.good' as status,
       sum(case when q1 = 'v.good' then 1 end) as q1,
       sum(case when q2 = 'v.good' then 1 end) as q2,
       sum(case when q3 = 'v.good' then 1 end) as q3,
       sum(case when q4 = 'v.good' then 1 end) as q4,
       sum(case when q5 = 'v.good' then 1 end) as q5
from tbl
union all
select 'good',
       sum(case when q1 = 'good' then 1 end) as q1,
       sum(case when q2 = 'good' then 1 end) as q2,
       sum(case when q3 = 'good' then 1 end) as q3,
       sum(case when q4 = 'good' then 1 end) as q4,
       sum(case when q5 = 'good' then 1 end) as q5
from tbl
union all
select 'fair',
       sum(case when q1 = 'fair' then 1 end) as q1,
       sum(case when q2 = 'fair' then 1 end) as q2,
       sum(case when q3 = 'fair' then 1 end) as q3,
       sum(case when q4 = 'fair' then 1 end) as q4,
       sum(case when q5 = 'fair' then 1 end) as q5
from tbl

答案 1 :(得分:0)

假设您想要计算行数,可能在应用程序层中更容易完成,但您可以这样做:

select status, sum(q1), sum(q2), sum(q3), sum(q4), sum(q5)
from (select q1 as status, 1 as q1, 0 as q2, 0 as q3, 0 as q4, 0 as q5 from table union all
      select q2, 0, 1, 0, 0, 0 from table union all
      select q3, 0, 0, 1, 0, 0 from table union all
      select q4, 0, 0, 0, 1, 0 from table union all
      select q5, 0, 0, 0, 0, 1 from table 
     ) q
group by status;

答案 2 :(得分:0)

我建议使用PIVOT and UPIVOT operators,如下所示:

要取消存储数据:

  SELECT id, Question, Answer
  FROM (
    SELECT id, q1, q2, q3, q4, q5
    FROM Answers
    ) AS pvteddata
  UNPIVOT(Answer FOR Question IN(q1, q2, q3, q4, q5)) AS unpvted 

以上查询返回:

id  Question    Answer
1   q1  v.good
1   q2  good
1   q3  fair
1   q4  good
1   q5  fair
2   q1  good
2   q2  v.good
2   q3  fair
2   q4  good
2   q5  fair
3   q1  v.good
3   q2  good
3   q3  fair
3   q4  good
3   q5  good
4   q1  good
4   q2  v.good
4   q3  good
4   q4  good
4   q5  v.good
5   q1  v.good
5   q2  good
5   q3  good
5   q4  good
5   q5  fair
6   q1  good
6   q2  v.good
6   q3  v.good
6   q4  good
6   q5  fair

现在,你应该再次转动它:

SELECT Answer, q1, q2, q3, q4, q5
FROM (
    -- above query
 ) AS DT
PIVOT(COUNT(Question) FOR Answer IN(q1, q2, q3, q4, q5)) AS PT