sql server pivot query - help required -


i need write sql server query pivot data source table.

my source table looks -

cust_id  item1_desc_count   item2_desc_count   item3_desc_count -------  ----------------   ----------------   ------------ cust1    10                 12                 9 cust2    7                  1                  3 cust3    12                 6                  0 ... 

item master table looks -

item_id item_desc ------- --------- 1       item1_desc 2       item2_desc 3       item3_desc  

please note item descriptions used in column names in source table.

and need output -

cust_id   item_id   count --------  --------- ------ cust1     1         10 cust1     2         12 cust1     3         9 cust2     1         7 cust2     2         1 cust2     3         3 cust3     1         12 ...  

can me achieve using sql query?

this more dynamic approach. no need specify item count columns.

the cross apply unpivot source table.

i should add unpivot more performant, i'm assuming have many count columns.


create sample data

declare @source table (cust_id varchar(25),item1_desc_count int,item2_desc_count int,item3_desc_count int) insert @source values ('cust1',10,12,9), ('cust2', 7, 1,3), ('cust3',12, 6,0)  declare @item table (item_id int,item_desc varchar(50)) insert @item values (1,'item1_desc'), (2,'item2_desc'), (3,'item3_desc') 

code example

select b.cust_id       ,c.item_id       ,count = b.value   (select xmldata = cast((select * @source xml raw) xml))  cross apply (                 select cust_id = r.value('@cust_id','varchar(50)')                       ,item    = attr.value('local-name(.)','varchar(100)')                       ,value   = attr.value('.','varchar(max)')                    a.xmldata.nodes('/row') a(r)                  cross apply a.r.nodes('./@*') b(attr)                  attr.value('local-name(.)','varchar(100)') not in ('cust_id','otherfieldstoexclude')              ) b  join @item c on b.item c.item_desc+'%' 

returns

cust_id item_id count cust1   1       10 cust1   2       12 cust1   3       9 cust2   1       7 cust2   2       1 cust2   3       3 cust3   1       12 cust3   2       6 cust3   3       0 

edit - unpivot option

select a.cust_id       ,b.item_id       ,count = a.value  (         select cust_id,item,value         @source          unpivot ( value item in (item1_desc_count,item2_desc_count,item3_desc_count) ) u         ) join @item b on a.item b.item_desc+'%' 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -