sql server - Pivot millons of records -


i have table 4 columns , more 100 million records. table design:

id char(12) pk  type char(2) pk (values 1,2,3) dcid varchar(10) null ind varchar(2) null (values y, n) 

this needs pivoted like

id, dcid1, dcid2, dcid3, ind1, ind2, ind3 

if type having value 1,then in pivoted table dcid1 should have value or if type 2 dcid2 should have value , on. correspoding ind needs placed in ind1, ind2, ind3 that.

how pivot this?

my suggestion @ using both unpivot , pivot functions result.

the unpivot used convert dci , ind multiple columns multiple rows in single column. once done, can pivot data columns.

the unpivot code similar this:

select id,   col +type new_col,   value (   select id,     type,      dcid,      cast(ind varchar(10)) ind   yt ) d unpivot (   value   col in (dcid, ind) ) unpiv; 

see sql fiddle demo. gives result:

|           id | new_col | value | ---------------------------------- | 1            |  dcid1  |  test | | 1            |   ind1  |     y | | 2            |  dcid2  |   est | | 2            |   ind2  |     y | 

the new_col contains dcid , ind names , has type value concatenated end. new value apply pivot to:

select id, dcid1, dcid2, dcid3, ind1, ind2, ind3 (   select id,     col +type new_col,     value     (     select id,       type,        dcid,        cast(ind varchar(10)) ind     yt   ) d   unpivot   (     value     col in (dcid, ind)   ) unpiv ) src pivot (   max(value)   new_col in (dcid1, dcid2, dcid3, ind1, ind2, ind3) ) piv; 

see sql fiddle demo. result be:

|           id | dcid1 | dcid2 | dcid3 | ind1 | ind2 | ind3 | ------------------------------------------------------------- | 1            |  test |       |       |    y |      |      | | 2            |       |   est |       |      |    y |      | | 3            |       |       |  blah |      |      |    y | | 4            |   yes |       |       |    n |      |      | | 5            |       |    hs |       |      |    n |      | | 6            |       |       |    jr |      |      |    n | 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -