簡體   English   中英

從三個單獨的表中收集數據,SQL

[英]Gathering data from three separate tables, sql

我有三個單獨的表格,分別代表三個星期的學生出勤情況。 我希望能夠生成四列,按每周細分每個學生的出勤率。 如果一個學生每周出席多次,則應增加出席的次數。 另外,如果一個學生在一個星期內出席,而不是在下一個星期內出席,那么該月的出席人數將為1(假設只出席一次),缺席的則為0。 我嘗試過count()和join的多種變體,但無濟於事。 任何幫助將不勝感激。 以下是截斷的小提琴:

http://www.sqlfiddle.com/#!9/b847a

這是我要達到的目標的一個示例:

Name | CurrWeek | LastWeek | TwoWkAgo

Paula | 0 | 2 | 3

一周中只有一個帶有一列的表,而不是三個表。 因此,自然可以滿足您要求的一種解決方案是使用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不支持此連接。無論如何,我的建議是更改數據模型。)

您可以嘗試以下查詢:

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個出勤表包含姓名作為公用字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM