tsql - Converting Rows to Columns in SQL SERVER 2008 -


in sql server 2008,

i have table tracking status history of actions (status_history) has 3 columns ([action_id],[status],[status_date]).

each action_id can have variable number of statuses , status dates.

i need convert these rows columns preferably this:

[action_id], [status_1], [status_2], [status_3], [date_1], [date_2], [date_3] 

where total number of status columns , date columns unknown, , - of course - date_1 correlates status_1, etc. , i'd status in chronological order (status_1 has earliest date, etc.)

my reason doing can put 10 recent statuses on report in access adp, along other information each action. using subreport each status in new row cause report far large.

is there way using pivot? don't want use date or status column heading.

is possible @ all?

i have no idea begin. it's making head hurt.

let suppose brevity want 3 recent statuses each action_id (like in example).

then query using cte should job:

with rownrs (  select    action_id   ,status   ,status_date   ,row_number() on (partition action_id order status_date desc) rownr    status_history )  select   s1.action_id action_id   ,s1.status status_1  ,s2.status status_2  ,s3.status status_3   ,s1.status_date date_1  ,s2.status_date date_2  ,s3.status_date date_3   (select * rownrs rownr=1) s1   left join (select * rownrs rownr=2) s2  on s1.action_id = s2.action_id   left join (select * rownrs rownr=3) s3  on s1.action_id = s3.action_id 

null values appear in rows action_id has less 3 status-es.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -