将2个SQL行转置到没有单个记录行的列

时间:2016-05-24 18:37:08

标签: sql-server tsql pivot case transpose

我试图设计一个查询来在SQL中转置下表:

|Name| |Type|
  A       X
  B       X
  C       Y
  D       Y
  E       Z

输出:

|X|  |Y|  |Z|
 A    C    E
 B    D  <Blank>

但我最终得到的是枢轴或最大案例陈述:

  |X|  |Y|  |Z|
   A   Null Null
   B   Null Null
  Null  C   Null
  Null  D   Null
  Null Null  E
这可能吗?提前致谢;

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT MAX(CASE WHEN Type = 'X' THEN Name END),
       MAX(CASE WHEN Type = 'Y' THEN Name END),
       MAX(CASE WHEN Type = 'Z' THEN Name END)
FROM (
  SELECT Name, Type, 
         ROW_NUMBER() OVER (PARTITION BY Type ORDER BY (SELECT NULL)) AS rn
FROM mytable) AS t
GROUP BY rn

答案 1 :(得分:0)

如果由于某种原因你有[名称],[类型]记录并且只想看一个,你会使用DENSE_RANK而不是ROW_NUMBER。这也是PIVOT版本。

SELECT  [X], [Y], [Z] 
FROM    (
    SELECT  [Name], [Type], 
            DENSE_RANK() OVER( PARTITION BY [Type] ORDER BY [Name]) Rn
    FROM    Table1) t 
PIVOT (
    MAX([Name])
    FOR [Type] IN ([X], [Y], [Z])) p