计算查询中的多个列

时间:2016-02-17 09:59:13

标签: mysql

伙计们我有四个问题:

查询#1:

select 
satisfaction_score,count(satisfaction_score) as Satisfaction_count
from j_survey_response
where satisfaction_score != 0
group by satisfaction_score

输出

satisfaction_score    Satisfaction_count
4                         329
5                         859

查询#2:

select 
response_score,count(response_score) as response_count
from j_survey_response
where response_score != 0
group by response_score

输出

response_score  response_count
3                    42
5                   980

查询#3:

select 
responder_score,count(responder_score) as responder_count
from j_survey_response
where responder_score != 0
group by responder_score

输出

responder_score  responder_count
4                    236
5                    987

查询#4:

select 
service_score,count(service_score) as service_count
from j_survey_response
where service_score != 0
group by service_score

输出

service_score    service_count
5                    966

但我需要输出如下

score  satisfaction_count  response_count  responder_count  service_count
3         null                  42            null             null
4          329                null             236             null
5          859                 980             986              966

提前致谢

1 个答案:

答案 0 :(得分:0)

试试这个:

select score,
        max(if(score_type='satisfaction_score',count,null)) as satisfaction_count,
        max(if(score_type='response_score',count,null)) as response_count,
        max(if(score_type='responder_score',count,null)) as responder_count,
        max(if(score_type='service_score',count,null)) as service_count
from (
    select score,count(satisfaction_score) as count,'satisfaction_score' as score_type from j_survey_response where satisfaction_score != 0 group by satisfaction_score
    union all
    select score,count(response_score) ,'response_score' as score_type from j_survey_response where response_score != 0 group by response_score
    union all
    select score,count(responder_score) ,'responder_score' as score_type from j_survey_response where responder_score != 0 group by responder_score
    union all
    select score,count(service_score) ,'service_score' as score_type from j_survey_response where service_score != 0 group by service_score
) as scores
group by scores.score