【问题标题】:Gathering data from two different tables, Sql从两个不同的表中收集数据,Sql
【发布时间】:2018-06-28 06:59:56
【问题描述】:

我有两个单独的表格,分别代表两周的学生出勤率。我想生成两列,按周划分每个学生的出勤率。如果学生每周多次出现,则应添加出现次数。此外,如果一个学生在一周内而不是下一周在场,那么当月的学生会得到 1(假设它只出现一次),缺席的学生会得到 0。我尝试了 count() 和 joins 的多种变体,但无济于事。任何帮助将不胜感激。以下是截断的小提琴:

http://www.sqlfiddle.com/#!9/36a6e0

这是我想要实现的示例:

Name | CurrWeek | LastWeek

Paula | 0 | 2

【问题讨论】:

  • 欢迎使用 Stack Overflow,它不是免费的代码编写或作业服务。您至少还应该向我们展示预期的输出是什么。
  • mysql 和 sql server 不同,请重新标记
  • 您应该添加您的尝试和所需的输出以获得更好的解决方案。
  • @ArsmanAhmad,在联合中“添加尝试”?
  • @TimBiegeleisen,不是作业。对不起,我最初没有包含足够的信息,这是我的第一篇文章。刚刚添加了预期的输出。

标签: mysql sql sqlite


【解决方案1】:

试试这个

两张桌子

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

【讨论】:

  • 谢谢,这行得通。我将如何向其中添加其他表格。例如,如果我有三个表而不是两个:sqlfiddle.com/#!9/b847a
  • 您可以添加任何编号。在内联视图中的表并在外部查询中添加这些列在答案中添加了第三个表
【解决方案2】:

你需要加入和计数,合并两个结果集需要联合

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

http://www.sqlfiddle.com/#!9/36a6e0/25

【讨论】:

  • 感谢您的回复。我会调查这个。
  • 我怎样才能在其中添加其他表格。例如,如果我再添加一个表,总共三个:sqlfiddle.com/#!9/4fea08
  • @MiddleZ 我认为你需要适当的数据库设计知识而不是添加越来越多的表,对于考勤相关的设计你可以点击这个链接stackoverflow.com/questions/3939764/…
  • 谢谢。但是,我不是在设计这个数据库,而是在使用我所拥有的。我的数据库比出勤更复杂。这是我为简化数据库包含的数据而制作的模拟数据库。您的 2 个表格的示例很有帮助,如果您能解释三个表格,我将不胜感激。提前致谢。
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
相关资源
最近更新 更多