如何使用 Sql 查询 CASE 语句将行值作为列获取

How to get row values as columns using Sql Query CASE statement

我有一个table

s_id   student_name attendance_date status
1        student1     2020-01-01     P
2        student1     2020-01-02     P
3        student2     2020-01-01     P
4        student2     2020-01-02     A

我希望我的 table 成为

s_id    student_name   01-01-2020   02-01-2020
1       student1       P             P
2       student2       P             A

我试过使用 CASE WHEN 语句,但学生的名字一直在重复。如何在不重复学生姓名的情况下得到结果?

尝试以下操作,这里是 DEMO。我没有包括 s_id 因为在这里包括它没有任何意义。

select
    student_name,
    max(case when attendance_date='2020-01-01' then status end) as '01-01-2020',
    max(case when attendance_date='2020-01-02' then status end) as '01-02-2020'
from yourTable
group by
    student_name

要对固定的日期列表进行透视,您可以进行条件聚合:

select
    s_id, 
    student_name,
    max(case when attendance_date = '2020-01-01' then status end) `2020-01-01`,
    max(case when attendance_date = '2020-01-02' then status end) `2020-01-02`
from mytable
group by s_id, student_name
order by s_id