转置Microsoft SQL Server表

时间:2014-04-16 14:30:36

标签: sql sql-server tsql pivot

我有两个表,一个标题表和一个详细信息表。数据如下所示:

    OBJ_NO | Name
    12345  | Fred
    67891  | Bob

Detail表:

    OBJ_NO | HEADER_OBJ_NO | CODE
    1      | 12345         | Red
    2      | 12345         | Blue
    3      | 12345         | Green
    4      | 67891         | Red
    5      | 67781         | Green    

基本上我所追求的是看到这样的东西:

    OBJ_NO | Name | Red | Blue | Green
    12345  | Fred | 1   | 1    | 1
    67891  | Bob  | 1   | 0    | 1

也可能是不同数量的“颜色”。它没有设定。并不是每个Header Ref都有一种颜色,如上例所示。

我将如何实现这一目标?

1 个答案:

答案 0 :(得分:-1)

SQL Server PIVOT适合您。

  WITH CTE(OBJ_NO, NAME, RED, BLUE, GREEN)
  AS
  (
  SELECT [OBJ_NO]
      ,[NAME]
      ,[red],[blue],[green]
  FROM (SELECT T2.[OBJ_NO]
      ,T2.[NAME], T1.CODE FROM [dbo].[Table_2] T2
   INNER JOIN [dbo].[Table_1] T1 ON T1.HEADER_OBJ_NO = T2.OBJ_NO ) AS SourceTable
   PIVOT
   (MAX(CODE) 
   FOR CODE IN ([red], [blue], [green])
   )AS PivotTable
   )
   SELECT OBJ_NO
   ,NAME
   ,RED = CASE WHEN RED = 'red' THEN 1 ELSE 0 END
   ,BLUE = CASE WHEN BLUE = 'blue' THEN 1 ELSE 0 END
   ,GREEN = CASE WHEN GREEN = 'green' THEN 1 ELSE 0 END
   FROM CTE