【问题标题】:Merge multiple records in single row合并单行中的多条记录
【发布时间】:2015-07-27 14:04:26
【问题描述】:

我试图让两个单独的记录显示在一行上,但不断得到多行带有空值的行。我认为如果按 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

【问题讨论】:

    标签: sql oracle oracle11g group-by null


    【解决方案1】:

    您似乎想要一个名称作为日期和名称,因此只将它们包含在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 标准格式。

    【讨论】:

      【解决方案2】:

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

      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;
      

      【讨论】:

        猜你喜欢
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-14
        • 2018-08-06
        • 2023-04-03
        • 1970-01-01
        相关资源
        最近更新 更多