2016-02-17 49 views
0

專家多個列我有四個查詢:計數在查詢

查詢#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 

OUTPUT

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 

OUTPUT

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 

OUTPUT

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 

在此先感謝

+0

如果你喜歡,可以考慮下列行爲這個簡單的兩步過程:1 。如果您還沒有這樣做,請提供適當的DDL(和/或sqlfiddle),以便我們可以更輕鬆地複製問題。 2.如果您尚未這樣做,請提供與步驟1中提供的信息相對應的所需結果集。 – Strawberry

+2

看起來與您之前的問題非常相似http://stackoverflow.com/questions/35431072/count-multiple -columns-in-one-queries –

+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