1

Thanks for reading.

I need to export data via SQL to XML. But I need the XML format in Row/column and the output must be a Pivot table. I know that it can be done with AS pivot. But I don't know how to use it in the below script

I've already got a fantastic script with the outcome in Row/Column format, but the output must be in 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

the above query needs to be in the same XML format(Row/Clolumn) but then in a Pivot table structure.

The desired outcome:

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

(whithout the ..............)

The desired outcome in 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>

Is this possible?

Thanks in advance.

Regards,

Bart

user3248190
  • 101
  • 1
  • 10
  • Check this out http://stackoverflow.com/questions/21163556/pivot-table-for-account-data-with-columns-for-each-month – IndoKnight Feb 06 '14 at 10:46

1 Answers1

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

Credits to:

Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com

user3248190
  • 101
  • 1
  • 10