简体   繁体   中英

MySQL combining multiple rows into one row

I've two tables as below:
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 

I need to join these two tables combining multiple rows for each month for each student from tbl_attendance into a single row to obtain a result like this:

 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

Thanks in advance for any help.

Instead of displaying month value in each of the records,
you can use them as column headers and attendance as their value.

Use pivot type solution to achieve required solution.

Example :

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

Your question is not very complete, but i think you want something like this:

 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

The previous code is used if you want to show all months in one column. For multiple columns, you can use this example:

  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

Do this for all the 12 months. I used 3 as example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM