Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

SQL Pivot utilizzando una colonna XML

Ecco un semplice esempio di negozi con dettagli del prodotto archiviati in xml. Il pivot è in basso che mostra i negozi e una somma di prezzo per categorie A e 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