2017-03-15 64 views
0

這是我在PIVOT語句中給出錯誤的腳本。我瘋了,不知道那裏有什麼問題。有人可以幫忙嗎?PIVOT語句中的TSQL錯誤

SELECT p.id, p.ln, p.fn, p.sc, p.gr, p.TestName, p.testgrade, 
       'CA Eng. Lang. Dev. Test' as Overall, 'List. & Speaking' as Speak, 'Reading', 
                 'Writing', 'Listening', 'Speaking', 'Comprehension', 'CELDT Criterion' as CELDT_criterion 
    FROM 
       (
        select * 
        from (
            select s.id,s.ln,s.fn,s.sc, s.gr 
          , t.id as TestName 
          , (t.gr/10) as testgrade 
          , CONVERT(varchar,t.td,101) as testdate 
          --, t.pt as testpart -- 0 is overall 
          , c.nm as testdesc 
          , t.ss as testscore 
          --, t.ot as profLevel        
            , row_number() over (partition by c.nm,DATEPART(MM, t.td) order by t.td desc) as rn 
            from tst t 
            JOIN Stu s ON s.id = t.pid 
            JOIN ctl c ON t.id = c.id and t.pt = c.pt 
            where 
            t.PID = 2062921 and 
            s.tg = ' ' and 
            t.ID in ('CELDT') 
        ) t2 
        where t2.rn = 1 
      ) s 
PIVOT 
(
    MAX(testscore) FOR testdesc IN ('CA Eng. Lang. Dev. Test', 'List. & Speaking', 'Reading', 
                 'Writing', 'Listening', 'Speaking', 'Comprehension', 'CELDT Criterion') 
) p 
+0

什麼是錯誤?另外,你使用的是什麼RDBMS?看起來像SQL Server,但是什麼版本? –

回答

2

我認爲這就是你想要的。請記住,在數據透視中,您使用[和]來指定字段名稱,這些名稱確實是您的測試名稱。此外,我不得不說,測試部分,因爲這不是唯一的,這導致了許多行(從樞軸)。

SELECT p.id, p.ln, p.fn, p.sc, p.gr, p.TestName, p.testgrade, 
      [CA Eng. Lang. Dev. Test] as Overall, [List. & Speaking] as Speak, [Reading], 
                [Writing], [Listening], [Speaking], [Comprehension], [CELDT Criterion] as CELDT_criterion 
FROM 
      (
       select * 
       from (
           select s.id,s.ln,s.fn,s.sc, s.gr 
           , t.id as TestName 
           , (t.gr/10) as testgrade 
           , CONVERT(varchar,t.td,101) as testdate 
           --, t.pt as testpart -- 0 is overall 
           , c.nm as testdesc 
           , t.ss as testscore 
           --, t.ot as profLevel 
           , row_number() over (partition by c.nm,DATEPART(MM, t.td) order by t.td desc) as rn 
           from tst t 
           JOIN Stu s ON s.id = t.pid 
           JOIN ctl c ON t.id = c.id and t.pt = c.pt 
           where 
           t.PID = 2062921 and 
           s.tg = ' ' and 
           t.ID in ('CELDT') 
       ) t2 
       where t2.rn = 1 
     ) s 
PIVOT 
(
    MAX(testscore) FOR testdesc IN ([CA Eng. Lang. Dev. Test], [List. & Speaking], [Reading], 
                [Writing], [Listening], [Speaking], [Comprehension], [CELDT Criterion]) 
) p 
+0

謝謝!我意識到測試部分和專業水平,但[]絕對是一個複習。 :) 再次感謝。 – Kaur

+0

這裏發生了什麼?你從哪裏得到' - ,t.pt作爲測試部分 - 0從整體來看是否是最初發布時的原始問題......? –

+0

@KubaWyrostek原創問題已編輯, – Kaur