2016-02-07 3 views
2

Таблица t1MySQL для подсчета

col1 col2 col3 
---- ---- ---- 
    1 cat 2 
    2 dog 3 
    3 cat 4 
    4 dog 5 

Таблица t2

id type 
---- ---- 
    1 a 
    2 a 
    3 b 
    4 b 

Я хочу, чтобы преобразовать его так, что он становится этим:

col2 a b 
---- ---- ---- 
cat 2 4 
dog 3 5 

Q uery

Select t1.col2, 
case when t2.type = 'a' then count(t1.col3) end as a, 
case when t2.ab = 'b' then count(t1.col3) end as b 
From mytable t1 join mytable2 t2 on t1.col1=t2.id where t1.col3 is not null 
group by 1; 

Это заполнит только А или В колонке.

Что не так с моим запросом?

ответ

1

Вы должны переместить случай заявление в графу() (или сумма()) сам:

Select t1.col2, 
     count(case when t2.type = 'a' then 1 else null end) as a, 
     count(case when t2.type = 'b' then 1 else null end) as b 
From mytable t1 join mytable2 t2 on t1.col1=t2.id where t1.col3 is not null 
group by 1; 
Смежные вопросы