我有三个单独的表格,分别代表三个星期的学生出勤情况。我希望能够生成四列,按每周细分每个学生的出勤率。如果一个学生每周出席多次,则应增加出席的次数。另外,如果一个学生在一个星期内出席,而不是在下一个星期内出席,那么该月的出席人数将为1(假设只出席一次),缺席的则为0。我尝试过count()和join的多种变体,但无济于事。任何帮助将不胜感激。以下是截断的小提琴:
http://www.sqlfiddle.com/#!9/b847a
以下是我要达到的目标的一个示例:
Name | CurrWeek | LastWeek | TwoWkAgo
Paula | 0 | 2 | 3
答案 0 :(得分:2)
一周中只有一个带有一列的表,而不是三个表。因此,针对您的请求的一种自然解决方案是使用UNION ALL
即时构建该请求:
select
name,
sum(week = 'currentWeek') as currentWeek,
sum(week = 'lastWeek') as lastWeek,
sum(week = 'thirdWeek') as thirdWeek
from
(
select 'currentWeek' as week, name from currentWeek
union all
select 'lastWeek' as week, name from lastWeek
union all
select 'thirdWeek' as week, name from thirdWeek
) all_weeks
group by name
order by name;
(如果您想连接三个表,则需要完全外部联接,如果我没记错的话,MySQL不支持该外部联接。无论如何,我的建议是更改数据模型。)
答案 1 :(得分:0)
您可以尝试以下查询:
select currweek.name, currweek.att, lastweek.att, twoWkAgo.att from
(select name, count(attendance) as att from currentWeekTable group by name) currweek,
(select name, count(attendance) as att from lastWeekTable group by name) lastweek,
(select name, count(attendance) as att from twoWeekTable group by name) twoWkAgo
where twoWkAgo.name=currWeek.name and twoWkAgo.name=lastweek.name;
假设您的3个出勤表包含姓名作为公用字段。