2013-03-24 3 views
1

Я хочу считать отличительные значения в качестве оценки. Значения, которые я хочу подсчитать, составляют от 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

+0

Да, см. Вторую часть ответа –

+0

Отлично! Я очень благодарен ! – Nyfiken