SSIS / SQL中列数据类型的数据透视表

时间:2017-02-02 10:56:54

标签: sql sql-server tsql ssis pivot

我的任务是转换下表:

    +---------------+----------+---------+-------------+-----+-------------+--------+
    | AnnualRevenue |   City   | Company | CreatedDate | Id  | IsConverted | UserId |
    +---------------+----------+---------+-------------+-----+-------------+--------+
    | NULL          | New York | ABC     | 1/03/2015   | 123 |           0 | A1     |
    | 200           | NULL     | DEF     | 2/03/2016   | 456 |           1 | A1     |
    +---------------+----------+---------+-------------+-----+-------------+--------+

在SQL查询或SSIS中:

+-----+---------------+----------+-----------+------+------+--------+
| Id  |     name      | nvarchar |   date    | int  | bit  | UserId |
+-----+---------------+----------+-----------+------+------+--------+
| 123 | AnnualRevenue | NULL     | NULL      | NULL | NULL | A1     |
| 123 | City          | New York | NULL      | NULL | NULL | A1     |
| 123 | Company       | ABC      | NULL      | NULL | NULL | A1     |
| 123 | CreatedDate   | NULL     | 1/03/2015 | NULL | NULL | A1     |
| 123 | IsConverted   | NULL     | NULL      | NULL | 0    | A1     |
| 456 | AnnualRevenue | NULL     | NULL      | 200  |      | A1     |
| 456 | City          | NULL     | NULL      | NULL | NULL | A1     |
| 456 | Company       | DEF      | NULL      | NULL | NULL | A1     |
| 456 | CreatedDate   | NULL     | 2/03/2016 | NULL | NULL | A1     |
| 456 | IsConverted   | NULL     | NULL      | NULL | 1    | A1     |
+-----+---------------+----------+-----------+------+------+--------+

我尝试在线研究并在SSIS中发现了PIVOT变换,但我以前从未使用过。我无法弄清楚如何使用它来达到预期的效果。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

此选项将动态地取消您的数据并将数据类型链接到信息架构。

我应该注意,XML字段名称ID和UserId区分大小写

示例

Select A.ID
      ,A.Name
      ,[nvarchar] = case when data_type='nvarchar' then value end
      ,[date]     = case when data_type='date'     then value end
      ,[int]      = case when data_type='int'      then value end
      ,[bit]      = case when data_type='bit'      then value end
      ,A.UserID
 From (
        Select C.*
         From  YourTable A
         Cross Apply (Select XMLData = cast((Select A.* For XML Raw) as xml)) B
         Cross Apply (
                        Select Id     = r.value('@Id','int')
                              ,UserID = r.value('@UserId','varchar(25)')
                              ,Name   = attr.value('local-name(.)','nvarchar(100)')
                              ,Value  = attr.value('.','nvarchar(max)') 
                         From  B.XMLData.nodes('/row') as A(r)
                         Cross Apply A.r.nodes('./@*') AS B(attr)
                         Where attr.value('local-name(.)','varchar(100)') not in ('Id','UserId')
                     ) C
       ) A
 Join (Select Column_Name,Data_Type From INFORMATION_SCHEMA.COLUMNS Where Table_Name='YourTable') B on B.Column_Name=A.Name

<强>返回

enter image description here