Mysql 从两个表中选择多列,其中一个表的一列具有多个where条件,并按两列对它们进行分组并按一进行排序
我有两个表,即“约会”和“技能数据” 预约表的结构如下:Mysql 从两个表中选择多列,其中一个表的一列具有多个where条件,并按两列对它们进行分组并按一进行排序,mysql,Mysql,我有两个表,即“约会”和“技能数据” 预约表的结构如下: id_ap || ap_meet_date || id_skill || ap_status. ap_状态值为完成、确认、取消和错过 而skills_数据表包含两列,即: id_skill || skill 我想得到每个条件下的预约总数 ap_status = ('complete' and 'confirm'), ap_status = 'cancel' and ap_status = 'missed' GROUP BY
id_ap || ap_meet_date || id_skill || ap_status.
ap_状态值为完成、确认、取消和错过
而skills_数据表包含两列,即:
id_skill || skill
我想得到每个条件下的预约总数
ap_status = ('complete' and 'confirm'),
ap_status = 'cancel' and
ap_status = 'missed'
GROUP BY id_skill and year and
order by year DESC
我尝试了这个查询,它只给我一个条件的计数,但我想根据上面提到的GROUPBY和ORDERBY子句得到另外两个条件
如果没有与特定条件匹配的记录(例如:某项技能在2018年错过了零次约会),则应显示零计数的输出值0
是否有人可以建议我使用一个查询,我是否应该实现多个select查询或CASE子句来实现我的预期结果。我在约会表中有很多记录,希望有一种高效的方法来查询我的记录。谢谢大家!
SELECT a.id_skill, YEAR(a.ap_meet_date) As year, s.skill,COUNT(*) as count_comp_conf
FROM appointment a,skills_data s WHERE a.id_skill=s.id_skill and a.ap_status IN ('complete', 'confirm')
GROUP BY `id_skill`, `year`
ORDER BY `YEAR` DESC
我的查询的输出:
id_skill | year | skill | count_comp_conf
-----------------------------------------
1 2018 A 20
2 2018 B 15
1 2019 A 10
2 2019 B 12
3 2019 C 10
我的预期输出应该如下所示:
id_skill | year | skill | count_comp_conf | count_cancel | count_missed
------------------------------------------------------------------------
1 2018 A 20 5 1
2 2018 B 15 8 0
1 2019 A 10 4 1
2 2019 B 12 0 5
3 2019 C 10 2 2
当表达式
SELECT a.id_skill, YEAR(a.ap_meet_date) As year, s.skill,
COUNT(case when a.ap_status IN ('complete', 'confirm') then 1 end) as count_comp_conf,
COUNT(case when a.ap_status = 'cancel' then 1 end) as count_cancel,
COUNT(case when a.ap_status = 'missed' then 1 end) as count_missed
FROM appointment a inner join skills_data s on a.id_skill=s.id_skill
GROUP BY `id_skill`, `year`
ORDER BY `YEAR` DESC
通过下面的查询,您将获得输出
select id_skill ,
year ,
skill ,
count_comp_conf ,
count_cancel ,
count_missed ( select id_skill, year, skill, if ap_status ='Completed' then count_comp_conf+1, elseif ap_status ='cancelled' then count_cancel +1 else count_missed+1
from appointment a join skills_data s on (a.id_skill = s.id_skill) group by id_skill, year) group by id_skill,year
order by year desc;
请尝试将if条件与sum一起使用。或sum(ap_status='cancel')@草莓,这确实是一个很好的条件,但大多数时候我忘记了这一点:)@fa06它很有效,非常感谢:)但只应删除最后一个条件后的逗号(我的意思是在第四行的count_遗漏之后).有理由假设答案与OP的问题相关,而无需明确说明。效果很好。谢谢:)在每个IF条件中,1,0意味着什么?在
IF
中,如果条件匹配,则每行返回1或0。然后使用求和函数。谢谢
SELECT a.id_skill,
YEAR(a.ap_meet_date) As year,
s.skill,
SUM(IF(a.ap_status IN ('complete', 'confirm'),1,0)) AS count_comp_conf,
SUM(IF(a.ap_status='cancel',1,0)) AS count_cancel,
SUM(IF(a.ap_status='missed',1,0)) AS count_missed
FROM appointment a,skills_data s WHERE a.id_skill=s.id_skill
GROUP BY `id_skill`, `year`
ORDER BY `YEAR` DESC;