2017-03-15 65 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