对于XML作为PIVOT

时间:2014-02-06 10:43:44

标签: sql xml

感谢阅读。

我需要通过SQL将数据导出到XML。但是我需要Row / column中的XML格式,输出必须是Pivot表。我知道可以用AS pivot完成。但我不知道如何在下面的脚本中使用它

我已经有一个很棒的脚本,结果是行/列格式,但输出必须是数据透视


    ;With CTE
    AS
    (
    SELECT [Name]
    ,[ColumnA]
    ,[ColumnB]
    ,[ColumnC]
    FROM Fact_A        INNER JOIN Dim_A on         
    Fact_A.Column_Key         =     Dim_A.Column_Key
    )
    select
    (
    select [Name] AS [@name],
    (select [ColumnA] as [column],
    null as tmp,
    ColumnB as [column],
    null as tmp,
    ColumnC  as [column]
    from CTE
    where [Name] = t.[Name]
    for xml path('row'),type) as [*]
    from (select distinct [Name] from CTE)t
    for xml path('variable'),root('data')
    ) as col_xml

上述查询需要采用相同的XML格式(行/列),然后才能使用数据透视表结构。

期望的结果:

    ........CellA...CellB
    companyA..4.......3
    companyB..0.......4
    companyC..1.......2

(无..............)

XML中的理想结果:


    <data>
    <variable name="Name">
    <row>
    <column></column>
    <column>A</column>
    <column>B</column>
    </row>
    <row>
    <column>companyA</column>
    <column>4</column>
    <column>3</column>
    </row>
    <row>
    <column>companyB</column>
    <column>0</column>
    <column>4</column>
    </row>
    <row>
    <column>companyC</column>
    <column>1</column>
    <column>2</column>
    </row>
    </variable>

这可能吗?

提前致谢。

此致

巴特

1 个答案:

答案 0 :(得分:0)

;With CTE
AS
(
SELECT [Name]
,[ColumnA]
,[ColumnB]
,[ColumnC]
FROM Fact_A
INNER JOIN Dim_A on
Fact_A.Column_Key = Dim_A.Column_Key
) , pvtClust as
(
select [Name], [ColumnA],
[A], [B]
from CTE
pivot (Sum(ColumnA) for
[Name] in ([A], [B])) pvt

)
select
(
select [Name] AS [@name],
(SELECT '' as [column]
, null as [tmp]
,'A' as [column]
, null as [tmp]
, 'B' as [column]
for xml path ('row'), type) as [*],
(select [Name] as [column],
null as tmp,
ISNULL([A], 0) as [column],
null as tmp,
ISNULL([B], 0) as [column]
from pvtClust
where [Name] = t.[Name]
for xml path('row'),type) as [*]
from (select distinct [Name] from CTE) t
for xml path('variable'),root('data')
) as col_xml

致记:

Russel Loski,MCT,MCSE数据平台/商业智能。 Twitter:@sqlmovers;博客:www.sqlmovers.com