sql server - Dynamic Columns in SQL Query with count and join -
i have 2 tables in sql server 2008 r2: table "phases:
phases_id phases_title ------------------------ 1 phase1 2 phase2 ... ...
and table "milestones"
milestones_id milestones_phaseid milestones_category ------------------------------------------------------ 1 1 project 2 1 project 3 1 customer ... ... ...
you can see 1:n relation between tables.
now need query result that:
phases_id project customer (columns 'project' , 'customer' counts milestones) --------------------------------- 1 2 1 2 0 3 ... ... ...
is there possibility create columns milestone categories dynamically? otherwise simple left join on tables , rest in code behind, performance worst.
thanks!
yes! pivot
rescue: http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
try this:
select phases_id, project, customer ( select phases_id, milestones_phaseid, milestones_category phases inner join milestones on phases_id = milestones_phaseid ) src pivot ( count(*) milestones_category in ([project], [customer]) ) pvt
Comments
Post a Comment