sql查询来获取参加的不同类的计数

时间:2014-06-05 07:12:09

标签: mysql sql

我有一个swim_attendance表

 student_name  date_attended cnt
 Bob             21-Aug-2013  1 
 Bob             10-Sep-2013  1 

我有一张karate_attendance表

 student_name  date_attended cnt
 Bob             20-Aug-2013  1
 Bob             21-Aug-2013  1
 Bob             21-Aug-2013  1

我正在努力计算每个学生的游泳出勤率和空手道出勤率

 student_name  swim_attendance  karate_attendance
 Bob               2              3

2 个答案:

答案 0 :(得分:2)

这是一种方法

select
student_name,
coalesce(sum(swim_attendance)) as swim_attendance,
coalesce(sum(karate_attendance)) as karate_attendance
from
(
  ( 
     select student_name,sum(cnt) as swim_attendance, 0 as karate_attendance
     from swim_attendance group by student_name
  )
  union all
  ( 
     select student_name,0 as swim_attendance, sum(cnt) as karate_attendance
     from karate_attendance group by student_name
  )
)x
group by student_name
;

<强> DEMO

更新:从Straberry提出的点到sum()只有一次

select
student_name,
coalesce(sum(swim_attendance)) as swim_attendance,
coalesce(sum(karate_attendance)) as karate_attendance
from
(
  ( 
     select student_name,cnt as swim_attendance, 0 as karate_attendance
     from swim_attendance 
  )
  union all
  ( 
     select student_name,0 as swim_attendance, cnt as karate_attendance
     from karate_attendance 
  )
)x
group by student_name
;

答案 1 :(得分:1)

你可以这样做

select s.student_name ,
sum(cnt * coalesce(s.table_type = 'swim') ) swim_attendance,
sum(cnt * coalesce(s.table_type = 'karate') ) karate_attendance
from (
select student_name , 'swim' as table_type,cnt from swim_attendance 
union all
select student_name ,'karate' as table_type,cnt from karate_attendance
) s
group by s.student_name

Demo