tsql - Sql Server: How do I unpivot with an alias? -


i know can use alias on column pivot, i'd use alias unpivot well.

select userid ,      contactmethod ,      contactmethodvalue users unpivot (     contactmethodvalue contactmethod in     (   homephone      [3000]     ,   officephone    [3001]     ,   cellphone      [3002]     ,   fax            [3003]     ,   website        [3005]     )  ) unpvt 

however error when this.

the way i've been able accomplish end goal use case statement in select clause, isn't pretty.

select userid ,      ( case contactmethod          when 'homephone'    3000          when 'officephone'  3001          when 'cellphone'    3002          when 'fax'          3003          when 'website'      3005          end ) contactmethod ,      contactmethodvalue users unpivot (     contactmethodvalue contactmethod in     (   homephone     ,   officephone     ,   cellphone     ,   fax     ,   website     )  ) unpvt 

is there better way?

you cannot assign alias inside of unpivot function have use case expression.

another way use union all , place new values immediately:

select userid, 3000 contactmethod, homephone contactmethodvalue users  union select userid, 3001 contactmethod, officephone contactmethodvalue users  union select userid, 3002 contactmethod, cellphone contactmethodvalue users  union select userid, 3003 contactmethod, website contactmethodvalue users  union select userid, 3005 contactmethod, homephone contactmethodvalue users  

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -