How to properly use pivot funciton to combine multiple values (or columns) into within one column in SQL Server? -


i have table contains upc, month# , week# these 3 main columns. (screenshot below)

enter image description here

is possible create view or display table groups week numbers 1 column each unique upc there many rows displayed. (example this)

enter image description here

do need use pivot function group grouping sets achieve this?

thanks.

sql fiddle

ms sql server 2008 schema setup:

query 1:

declare @table table (recordid int, upc bigint, monthnumberonpromo int, weeknumberonpromo int) insert @table values  (1  , 2529230005 , 1   , 1)  , (2  , 2529230005 , 2   , 6), (3  , 2529230005 , 3   , 11) , (4  , 2529230005 , 4   , 15), (5  , 2529230005 , 6   , 22) , (6  , 2529230005 , 7   , 27), (7  , 2529230005 , 8   , 31) , (8  , 2529230005 , 9   , 35), (9  , 2529230007 , 1   , 1)  , (10 , 2529230007 , 2   , 6), (11 , 2529230007 , 3   , 11) , (12 , 2529230007 , 4   , 15), (13 , 2529230007 , 6   , 22) , (14 , 2529230007 , 8   , 31), (15 , 2529230007 , 9   , 35) , (16 , 2529230007 , 10   , 38), (17 , 2529230007 , 12  , 51)  select * (     select t.upc           ,left(datename(month ,  '1900' + right('00'                         + cast(t.monthnumberonpromo nvarchar(2)),2) + '01') , 3)  [month]           ,'yes' value           ,stuff((select ',' + cast(weeknumberonpromo nvarchar(10))                   @table                   t.upc = upc                   xml path(''),type)                   .value('.','nvarchar(max)'),1,1,'') [week_list]     @table t     group t.upc              ,left(datename(month ,  '1900' + right('00'                          + cast(t.monthnumberonpromo nvarchar(2)),2) + '01') , 3)      )t pivot (max(value)        [month]        in ([jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec])       )p 

results:

|        upc |                week_list | jan | feb | mar | apr |    may | jun |    jul | aug | sep |    oct |    nov |    dec | |------------|--------------------------|-----|-----|-----|-----|--------|-----|--------|-----|-----|--------|--------|--------| | 2529230005 |    1,6,11,15,22,27,31,35 | yes | yes | yes | yes | (null) | yes |    yes | yes | yes | (null) | (null) | (null) | | 2529230007 | 1,6,11,15,22,31,35,38,51 | yes | yes | yes | yes | (null) | yes | (null) | yes | yes |    yes | (null) |    yes | 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

visual studio 2010 - Connect to informix database windows form application -

android - Associate same looper with different threads -