2013-03-24 221 views
1

我想將differen值計爲分數。我想要計算的數值是7到10.表中還有1到6個數字,但我不想數它們。我不明白。交叉表查詢

值如表是這樣的:

 
RPO RSP  RSV 
10  9  9 
9  10  8 
10  7  7 
7  10  8 
4  4  3 

我想要的結果是這樣的:

 
Score RPO RSP RSV 
10  2 2 0 
9  1 1 1 
7  1 1 1 

這裏是我的代碼。需要改進它。

select 

count(rank.rpo) as RPO, 
count(rank.rsp) as RSP, 
count(rank.rsv) as RSV 

from 
round 
left join base 
on round.id = base.round_id 

left join rank 
on round.id = rank.round_id and rank.number = base.number 

where 
base.result = 1 
and round.round_date between '2013-03-15' and '2013-03-22' 
and round.gameform = 'V4' 
and round.gameform not like "OSPEC" 

group by ?? 

回答

2

你可以嘗試這樣的事:

drop table if exists ids; 

create table ids (score int unsigned primary key) 
select distinct rpo as score from rank 
union 
select distinct rsp as score from rank 
union 
select distinct rsv as score from rank; 

select ids.score, 
     sum(if(rank.rpo=ids.score,1,0)) as RPO, 
     sum(if(rank.rsp=ids.score,1,0)) as RSP, 
     sum(if(rank.rsv=ids.score,1,0)) as RSV 
    from ids,round 
left join base on round.id = base.round_id 
left join rank on round.id = rank.round_id and rank.number = base.number 
where base.result = 1 
    and round.round_date between '2013-03-15' and '2013-03-22' 
    and round.gameform = 'V4' 
    and round.gameform not like "OSPEC" 
    group by ids.score with rollup; 

如果你不希望創建一個臨時表,你可以嘗試:

select ids.score, 
     sum(if(rank.rpo=ids.score,1,0)) as RPO, 
     sum(if(rank.rsp=ids.score,1,0)) as RSP, 
     sum(if(rank.rsv=ids.score,1,0)) as RSV 
    from 
    (
     select distinct rpo as score from rank 
     union 
     select distinct rsp as score from rank 
     union 
     select distinct rsv as score from rank 
) ids, round 
left join base on round.id = base.round_id 
left join rank on round.id = rank.round_id and rank.number = base.number 
where base.result = 1 
    and round.round_date between '2013-03-15' and '2013-03-22' 
    and round.gameform = 'V4' 
    and round.gameform not like "OSPEC" 
group by ids.score with rollup; 

的工作示例見http://sqlfiddle.com/#!2/9b7d7/6

+0

我可以不用創建表來做到這一點嗎? – Nyfiken 2013-03-24 21:29:01

+0

是的,看第二部分的答案 – 2013-03-24 21:35:10

+0

完美!我非常感謝! – Nyfiken 2013-03-25 08:09:25