请考虑以下示例表结构:
+-------------------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------------------+--------------+------+-----+---------+-------+
| msisdn | varchar(20) | NO | PRI | NULL | |
| job_search_text | varchar(500) | YES | | NULL | |
| local_job_region_id | int(11) | YES | MUL | NULL | |
| ....... | ....... | ... | ... | .... | .... |
| ....... | ....... | ... | ... | .... | .... |
| ....... | ....... | ... | ... | .... | .... |
| ....... | ....... | ... | ... | .... | .... |
| ....... | ....... | ... | ... | .... | .... |
| ....... | ....... | ... | ... | .... | .... |
+-------------------------------+--------------+------+-----+---------+-------+
我想按如下方式计算行数:
If job_search_text='a' then count row as 'A'
Else If job_search_text='b' then count row as 'B'
Else If job_search_text='c' then count row as 'C'
.
.
.
Else count row as 'Other'
我写的查询是:
SELECT COUNT(CASE WHEN job_search_text='a' THEN 1 END) as 'A',COUNT(CASE WHEN job_search_text='b' THEN 1 END) as 'b' FROM subscriber
但是这个查询比较了每个CASE的job_search_text,并且它也没有处理上面提到的Else情况。请帮帮我。
答案 0 :(得分:2)
你在正确的轨道上,但是将计数改为SUM(IF())......类似于
select
sum( if( s.job_search_text = 'a', 1, 0 ) ) as 'A',
sum( if( s.job_search_text = 'b', 1, 0 ) ) as 'B',
sum( if( s.job_search_text = 'c', 1, 0 ) ) as 'C',
sum( if( s.job_search_text = 'd', 1, 0 ) ) as 'D',
sum( if( s.job_search_text = 'e', 1, 0 ) ) as 'E',
sum( if( s.job_search_text IN ( 'a', 'b', 'c', 'd', 'e' ), 0, 1 ) ) as 'Other'
from
subscriber s
另一个的“IN”测试,如果找到已经考虑的东西,那么它就是零值。如果它找不到其中一个a-e条目,它会为你的“其他”计数加上一个。
答案 1 :(得分:0)
select count(*), job_Search_Text
FROM table
group by job_Search_text
每个job_Search_Text返回1行,计数如此...就没有“其他”
10 A
15 B
25 C
30 D
50 E
99 F