SQL透视一个不透明的表

时间:2017-11-12 23:03:10

标签: sql sql-server tsql

我有一张表格如下:

+----+------------+     
| ID | SchoolName |   
+----+------------+     
|  1 | abc        |     
|  1 | pqr        |    
|  1 | xyz        |     
|  2 | dfg        |     
|  2 | yui        |     
|  3 | gtr        |     
|  4 | fgh        |      
|  5 | erf        |     
|  6 | abc        |     
|  6 | fgy        |     
+----+------------+

我想将其作为

+----+--------------------+    
| ID | First Second Third |    
+----+--------------------+    
|  1 | abc   pqr    xyz   |    
|  2 | dfg   yui          |    
|  3 | gtr                |    
|  4 | fgh                |     
|  5 | erf                |    
|  6 | abc   fgy          |    
+----+--------------------+       

我写了查询

WITH cte AS (
  SELECT id, schoolname,      
  ROW_NUMBER() OVER(PARTITION BY id ORDER BY id) rn     
FROM dbo.Temp123         
  )    
  SELECT * FROM (   
 (SELECT id, schoolname,rn FROM cte) a    
 PIVOT    
(MAX(schoolname) FOR rn IN (1,2,3)) p

错误:

  

Msg 102,Level 15,State 1,Line 8'1'附近的语法不正确。

你能帮我解决这个问题。 感谢

2 个答案:

答案 0 :(得分:4)

你很亲密!试试这个:

;WITH cte AS (
  SELECT id, schoolname,
    ROW_NUMBER() OVER(PARTITION BY id ORDER BY id) rn
  FROM dbo.Temp123
)
SELECT *
FROM  (SELECT id, schoolname,rn FROM cte) a
  PIVOT (MAX(schoolname) FOR rn IN ([1],[2],[3])) p
  • 删除了方括号中的额外开括号和包装整数列标识符

rextester演示:http://rextester.com/GBBN40959

返回:

+----+-----+------+------+
| id |  1  |  2   |  3   |
+----+-----+------+------+
|  1 | abc | pqr  | xyz  |
|  2 | dfg | yui  | NULL |
|  3 | gtr | NULL | NULL |
|  4 | fgh | NULL | NULL |
|  5 | erf | NULL | NULL |
|  6 | abc | fgy  | NULL |
+----+-----+------+------+

答案 1 :(得分:0)

一种方法是使用row_number()。我会用条件聚合来做到这一点:

select id,
       max(case when seqnum = 1 then schoolname end) as schoolname_1,
       max(case when seqnum = 2 then schoolname end) as schoolname_2,
       max(case when seqnum = 3 then schoolname end) as schoolname_3
from (select t.*, row_number() over (partition by id order by (select null)) as seqnum
      from dbo.Temp123  t
     ) t
group by id;