合并两个行值并将行值转换为列标题

时间:2016-04-15 01:10:22

标签: sql-server

以下是我们正在使用的源表:

+-----------+-----------+------+----------+----------+  
| startdate | enddate   | Type | Planet   | Rotation |  
+-----------+-----------+------+----------+----------+  
| 4/4/2016  | 4/10/2016 | A1   | Netptune | P1       |  
| 4/4/2016  | 4/10/2016 | A2   | Netptune | P2       |  
| 4/4/2016  | 4/10/2016 | A3   | Netptune | P3       |  
| 4/4/2016  | 4/10/2016 | A4   | Netptune | P4       |  
| 4/4/2016  | 4/10/2016 | B1   | Saturn   | P1       |  
| 4/4/2016  | 4/10/2016 | B2   | Saturn   | P2       |  
| 4/4/2016  | 4/10/2016 | B3   | Saturn   | P3       |  
| 4/4/2016  | 4/10/2016 | B4   | Saturn   | P4       |  
| 4/4/2016  | 4/10/2016 | B5   | Saturn   | P5       |  
| 4/4/2016  | 4/10/2016 | C1   | Pluto    | P1       |  
| 4/4/2016  | 4/10/2016 | C2   | Pluto    | P2       |  
| 4/4/2016  | 4/10/2016 | C3   | Pluto    | P3       |  
| 4/4/2016  | 4/10/2016 | C4   | Pluto    | P4       |  
| 4/11/2016 | 4/17/2016 | D1   | Netptune | P1       |  
| 4/11/2016 | 4/17/2016 | D2   | Netptune | P2       |  
| 4/11/2016 | 4/17/2016 | D3   | Netptune | P3       |  
| 4/11/2016 | 4/17/2016 | D4   | Netptune | P4       |  
| 4/11/2016 | 4/17/2016 | E1   | Saturn   | P1       |  
| 4/11/2016 | 4/17/2016 | E2   | Saturn   | P2       |  
| 4/11/2016 | 4/17/2016 | E3   | Saturn   | P3       |  
| 4/11/2016 | 4/17/2016 | E4   | Saturn   | P4       |  
| 4/11/2016 | 4/17/2016 | E5   | Saturn   | P5       |  
| 4/11/2016 | 4/17/2016 | F1   | Pluto    | P1       |  
| 4/11/2016 | 4/17/2016 | F2   | Pluto    | P2       |  
| 4/11/2016 | 4/17/2016 | F3   | Pluto    | P3       |  
| 4/11/2016 | 4/17/2016 | F4   | Pluto    | P4       |  
+-----------+-----------+------+----------+----------+  

我要查找的Pivot查询将获取行星的行值并将其添加到旋转列中的值,并使其成为列标题。请参见下图查看输出表。

数据透视查询的结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用dynamic crosstab执行此操作:

DECLARE @sql NVARCHAR(MAX) = '';

SELECT @sql = 
'SELECT
      StartDate
    , EndDate' + CHAR(10)

SELECT @sql = @sql +
'   , MAX(CASE WHEN Planet = ''' + Planet + ''' AND Rotation = ''' +
         Rotation + ''' THEN Type END) AS ' + QUOTENAME(Planet + Rotation) + CHAR(10)
FROM(
    SELECT DISTINCT Planet, Rotation FROM tbl
) t
ORDER BY Planet, Rotation

SELECT @sql = @sql +
'FROM tbl
GROUP BY StartDate, EndDate
ORDER BY  StartDate, EndDate;'
;

EXEC (@sql);

ONLINE DEMO