从两个表中选择多个列,其中一个表的一个列具有多个where条件,并将它们按两列分组并按一个顺序排序

时间:2019-05-21 06:12:54

标签: mysql

我有两个表,分别是“约会”和“ skills_data”。

约会表的结构为:

id_ap || ap_meet_date || id_skill || ap_status. 

并且ap_status的值是完整的,确认,取消和遗漏的。

skills_data表包含两列,即:

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

我尝试了该查询,该查询仅给我一个条件的计数,但是我想根据提到的group by和order by子句获取其他两个条件。

如果没有符合特定条件的记录(例如:2018年缺少一项技能的零约会),则应显示零计数的输出值0。

有人可以向我提出查询建议我是否应该实现多个选择查询或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

3 个答案:

答案 0 :(得分:1)

您可以使用conditional aggregation来使用case when expression

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

答案 1 :(得分:1)

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;

请尝试使用if条件和总和。

答案 2 :(得分:-1)

通过以下查询,您将获得输出。

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;