Question

Quelqu'un a-t-il un exemple de pivot utilisant une table avec une colonne XML - transformant en particulier certains des éléments de la colonne xml en une colonne du tableau croisé dynamique? J'essaie d'en construire un, mais la syntaxe me tue; XML en SQL est extrêmement difficile à travailler, comparé à XML en C #. Je pense que c'est impossible, mais cela ne ferait pas de mal de vérifier:)

Était-ce utile?

La solution

Voici un exemple simple dans lequel les magasins avec les détails du produit sont stockés au format xml. Le pivot situé en bas indique les magasins et une somme de prix par catégories A et 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top