有没有人有一个使用带有XML列的表的数据透视示例 - 特别是将xml列中的某些元素转换为数据透视表中的一列?我正在尝试构建一个,但语法正在扼杀我;与C#中的xml相比,sql中的xml很难处理。我怀疑这是不可能的,但检查是不会有害的:)

有帮助吗?

解决方案

这是一个简单的示例,其中包含存储在xml中的产品详细信息。枢轴位于底部,显示商店和按类别A和B的价格总和。

declare @test Table
(

    StoreID int,
    ProdXml xml
)

insert into @test
select 1, '<product cat="A" name="foo" price="10" />' union
select 2, '<product cat="A" name="bar" price="12" />' union
select 1, '<product cat="B" name="blah" price="35" />' union    
select 2, '<product cat="B" name="bap" price="67" />' union
select 1, '<product cat="C" name="bip" price="18" />' union
select 2, '<product cat="A" name="bing" price="88" />' union
select 1, '<product cat="B" name="bang" price="34" />' union    
select 2, '<product cat="B" name="boom" price="65" />' 

--Pivot showing sum of price by Cat
select  StoreID, A, B
from
(   
    select  StoreID,
        ProdXml.value('/product[1]/@cat[1]','varchar(20)') as [ProdCat],
        ProdXml.value('/product[1]/@price[1]','int') as [ProdPrice]
    from  
        @test
) up
PIVOT (SUM([ProdPrice]) FOR [ProdCat] IN ( A, B)) as pvt
ORDER BY StoreID
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top