SQL查询将具有重复值的行转换为列

问题描述 投票:-3回答:1

源表:

Student_id  Student_name     attr_name      attr_value
100           Sam             Course_id     12345
100           Sam             startdate     2019-01-01 
100           Sam             enddate       2019-12-31
100           Sam             Ques1         Do you like this course?
100           Sam             ans1          Yes
100           Sam             Ques2         Provide a rating for this course?
100           Sam             ans2          10
.
.
.
.
100           Sam             Ques(N)        XXXX
100           Sam             ans(N)         YYYY

编写SQL查询以获得以下结果?

Student_id  Student_name    Course_id   start_date  end_date        Ques                                Ans
100         Sam           12345         2019-01-01  2019-12-31      Do you like this course?            Yes
100         Sam           12345         2019-01-01  2019-12-31      Provide a rating for this course?   10
.
.
.
.
100         Sam           12345         2019-01-01  2019-12-31      XXXX                                YYYY

我能拿到这里。但无法旋转最后两列。

Select 
Student_id, 
Student_name, 
max(case when attr_name = 'Course_id' then attr_value end) as Course_id,
max(case when attr_name = 'startdate' then attr_value end) as start_date,
max(case when attr_name = 'enddate'   then attr_value end) as end_date 
from Source 
group by 1,2
sql pivot
1个回答
0
投票

我不推荐这种桌子设计。关系数据库的优点是可以在表之间建立关系,然后再进行联接,因此您不必将所有内容都填充到一个表中。优点之一是每行都没有重复数据:100,“ Sam”。最好在这里至少有3张桌子;学生,课程,属性。

话虽这么说,您可以做这样的事情来模拟这种行为,我猜:

select 
student.student_id
,(select distinct student_name from Source s where s.student_id = student.student_id) as student_name
,(select attr_value from Source s where s.student_id = student.student_id and attr_name = 'course_id') as course_id
,(select attr_value from Source s where s.student_id = student.student_id and attr_name = 'start_date') as start_date
-- ETC. for every attribute
from (select distinct student_id, student_name from Source) student 
order by student_id
-- if you wanna order by an attr other than student_id, you have to write as the select above:
--order by (select attr_value from Source s where s.student_id = student.student_id and attr_name = 'course_id')

© www.soinside.com 2019 - 2024. All rights reserved.