合并多行记录

时间:2015-05-15 15:12:14

标签: sql oracle oracle11g group-by null

我试图让两条单独的记录显示在一行上,但不断获得多行的空值。我认为,如果我按Test_Date分组,我可以在每个测试日期获得一行,并且分数在一行上,但正如您所看到的,这对我来说无效。

如何将两行合并为一行,在阅读分数旁边显示数学分数?

SELECT st.test_date, t.name, decode(ts.name,'Mathematics', sts.numscore) as Mathematics,
decode(ts.name, 'Reading', sts.numscore) as Reading
FROM studenttestscore sts
     JOIN studenttest st ON sts.studenttestid = st.id
     JOIN testscore ts ON sts.testscoreid = ts.id
     JOIN test t on ts.testid = t.id
     JOIN students s ON s.id = st.studentid
WHERE t.id IN (601, 602, 603)
     AND s.student_number = '108156'
GROUP BY st.test_date, t.name, 
         decode(ts.name,'Mathematics', sts.numscore),
         decode(ts.name, 'Reading', sts.numscore)
ORDER BY st.test_date

--- CURRENT OUTPUT ---

Test_Date    Name        Mathematics    Reading
29-AUG-13    MAP FALL            227     (null)
29-AUG-13    MAP FALL         (null)        213
22-JAN-14    MAP WINTER          231     (null)
22-JAN-14    MAP WINTER       (null)        229
05-MAY-14    MAP SPRING          238     (null)
05-MAY-14    MAP SPRING       (null)        233

--- DESIRED OUTPUT ---

Test_Date    Name        Mathematics    Reading
29-AUG-13    MAP FALL            227        213
22-JAN-14    MAP WINTER          231        229
05-MAY-14    MAP SPRING          238        233

2 个答案:

答案 0 :(得分:3)

您似乎想要一个名称作为日期和名称,因此只能将它们包含在GROUP BY中。其余部分使用聚合函数:

SELECT st.test_date, t.name,
       MAX(CASE WHEN ts.name = 'Mathematics' THEN sts.numscore END) as Mathematics,
       MAX(CASE WHEN ts.name = 'Reading' THEN sts.numscore END) as Reading
FROM studenttestscore sts JOIN
     studenttest st
     ON sts.studenttestid = st.id JOIN
     testscore ts
     ON sts.testscoreid = ts.id JOIN
     test t
     ON ts.testid = t.id JOIN
     students s
     ON s.id = st.studentid
WHERE t.id IN (601, 602, 603) AND s.student_number = '108156'
GROUP BY st.test_date, t.name, 
ORDER BY st.test_date;

我还将decode()替换为CASE,这是用于在表达式中表达条件的ANSI标准格式。

答案 1 :(得分:1)

您必须使用Aggergate MAX()并按名称和testdate分组才能获得所需的结果

Sample SQL Fiddle

select t.test_date, 
        t.name, max(Mathematics) as Mathematics,
        max(Reading) as Reading 
from t
GROUP BY t.test_date, t.name
ORDER BY t.test_date;
相关问题