我有两个单独的表格,分别代表两个星期的学生出勤情况。我想生成两列,按每周细分每个学生的出勤率。如果一个学生每周出席多次,则应增加出席的次数。另外,如果一个学生在一个星期内出席,而不是在下一个星期内出席,那么该月的出席人数将为1(假设只出席一次),缺席的则为0。我尝试过count()和join的多种变体,但无济于事。任何帮助将不胜感激。以下是截断的小提琴:
http://www.sqlfiddle.com/#!9/36a6e0
以下是我要达到的目标的一个示例:
Name | CurrWeek | LastWeek
Paula | 0 | 2
答案 0 :(得分:0)
您需要加入并计数,并且要合并两个结果集,需要合并
select T1.name,T1.currentwk,T2.lasttwk from
(
select name,count(id) as currentwk from currentWeek
group by name
) as T1
left join
(
select name,count(id) as lasttwk from lastWeek
group by name
) as T2
on T1.name=T2.name
union
select T2.name,T1.currentwk,T2.lasttwk from
(
select name,count(id) as currentwk from currentWeek
group by name
) as T1
right join
(
select name,count(id) as lasttwk from lastWeek
group by name
) as T2
on T1.name=T2.name
答案 1 :(得分:0)
尝试一下
用于2个表
Select name, max(current_week) current_week, max(last_week) as last_week
From (
Select name, count(1) as current_week, 0 as last_week from currentWeek group by name
union all
Select name, 0 as current_week, count(1) as last_week from lastWeek group by name
) x
group by name
用于3个表
Select name, max(current_week) current_week, max(last_week) as last_week, max(third_week) as third_week
From (
Select name, count(1) as current_week, 0 as last_week, 0 as thrid_week from currentWeek group by name
union all
Select name, 0 as current_week, count(1) as last_week, 0 as thrid_week from lastWeek group by name
union all
Select name, 0 as current_week, 0 as last_week, count(1) as thrid_week from thirdWeek group by name
) x
group by name