这是我第一次使用这样的论坛进行SQL帮助,所以请耐心等待!我有一个用于学生数据的大型查询集,每个学生都有一行,其中主要连接表是他们的应用程序记录(所有其他表加入到该应用程序记录中)。现在,我正在寻找学位数据,但是很多学生都有多个学位,因此它会重复学生行(嘘!)。
以下是它的缩写版本:
StudentID CohortTerm DegreeYear DegreeMonth
1 2009 Spring 2011 05
1 2009 Spring 2013 10
2 2012 Fall 2015 05
3 2015 Fall 2017 05
3 2015 Fall 2018 05
这就是我想要的样子:
StudentID CohortTerm Degree1_Y Degree1_M Degree2_Y Degree2_M
1 2009 Spring 2011 05 2013 10
2 2012 Fall 2015 05
3 2015 Fall 2017 05 2018 05
答案 0 :(得分:1)
以下是使用分析函数执行此操作的另一种方法:
WITh test_data AS
(
SELECT 1 StudentID, 2009 Cohort, 'Spring' Term, 2011 DegreeYear, '05' DegreeMonth FROM dual
UNION ALL
SELECT 1, 2009, 'Spring', 2013, '10' FROM dual
UNION ALL
SELECT 2, 2012, 'Fall' , 2015, '05' FROM dual
UNION ALL
SELECT 3, 2015, 'Fall' , 2017, '05' FROM dual
UNION ALL
SELECT 3, 2015, 'Fall' , 2018, '05' FROM dual
)
SELECT * FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY Cohort ORDER BY Cohort, DegreeYear, DegreeMonth) rno
, StudentID, Cohort, Term, DegreeYear, DegreeMonth
, LEAD(DegreeYear) OVER (PARTITION BY Cohort ORDER BY Cohort, DegreeYear, DegreeMonth) DegreeYear2
, LEAD(DegreeMonth) OVER (PARTITION BY Cohort ORDER BY Cohort, DegreeYear, DegreeMonth) DegreeMonth2
FROM test_data
)
WHERE rno = 1
ORDER BY Cohort, DegreeYear, DegreeMonth
/
输出:
RNO STUDENTID COHORT TERM DEGREEYEAR DEGREEMONTH DEGREEYEAR2 DEGREEMONTH2
1 1 2009 Spring 2011 05 2013 10
1 2 2012 Fall 2015 05
1 3 2015 Fall 2017 05 2018 05
答案 1 :(得分:0)
正如其他人评论的那样,pivot
正是您所寻找的。请在此处查看pivot docs。