【问题标题】:MySQL combining multiple rows into one rowMySQL将多行合并为一行
【发布时间】:2015-09-07 21:58:29
【问题描述】:

我有两张表如下:
1. tbl_student:

id  name
1   raj
2   raja
3   raju
4   rajan
  1. tbl_attendance

     id student_id month attended_days
      1          1     1             6
      2          1     2            16
      3          8     1             8
      4          7     2            14
      5          8     2            13
      6          7     1            11
    

我需要将这两个表结合起来,将 tbl_attendance 中每个学生每个月的多行合并为一行,以获得如下结果:

 id     name    month   attended_days   month   attended_days
  1     raj         1               6       2              16
  7     raja        1              11       2              14
  8     rajan       1               8       2              13

提前感谢您的帮助。

【问题讨论】:

  • 我认为如果您添加一些代码来显示您尝试过的(但失败了)会有所帮助,这将增加您获得答案的机会
  • 你的结果最后应该包含多少month列?
  • 您需要的是一个数据透视表。这可以通过创建一个准备好的语句来实现,该语句将以您正在寻找的格式为您返回结果。

标签: mysql join rows


【解决方案1】:

而不是在每个记录中显示月份值,
您可以将它们用作列标题,并将出勤率用作它们的值。

使用 pivot 类型的解决方案来实现所需的解决方案。

示例

select s.id as student_id
     , s.name as student_name
     , max( case when a.month = 1 then a.attended_days else null end ) as month_1
     , max( case when a.month = 2 then a.attended_days else null end ) as month_2
     , max( case when a.month = 3 then a.attended_days else null end ) as month_3
--     ...
     , max( case when a.month = 12 then a.attended_days else null end ) as month_12
  from table_student s
  left join table_attendance a on s.id = a.student_id
 group by s.id, s.name

【讨论】:

    【解决方案2】:

    你的问题不是很完整,但我认为你想要这样的东西:

     select s.*, 
        coalesce(a1.month, a2.month, a3.month) as month,
        coalesce(a1.attended_days , a2.attended_days , a3.attended_days ) as attended_days 
         from table_student s
          left join table_attendance a1 on s.id = a1.student_id and a1.month = 1
          left join table_attendance a2 on s.id = a2.student_id and a2.month = 2
          left join table_attendance a3 on s.id = a3.student_id and a3.month = 3
    

    如果您想在一列中显示所有月份,则使用前面的代码。对于多列,您可以使用此示例:

      select s.*, 
        a1.month as month_1, 
        a2.month as month_2,
        a3.month  as month_3,
        a1.attended_days as attended_days_1, 
        a2.attended_days as attended_days_2, 
        a3.attended_days as attended_days_3  
         from table_student s
          left join table_attendance a1 on s.id = a1.student_id and a1.month = 1
          left join table_attendance a2 on s.id = a2.student_id and a2.month = 2
          left join table_attendance a3 on s.id = a3.student_id and a3.month = 3
    

    在所有 12 个月内都这样做。我以 3 为例。

    【讨论】:

      猜你喜欢
      • 2014-02-02
      • 2012-08-29
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-29
      • 1970-01-01
      相关资源
      最近更新 更多