Friday, 15 June 2012

Adding another column with a different condition in SQL -



Adding another column with a different condition in SQL -

i'm trying find different info info in same query. want create new columns based on separate conditions. here table looks right now

select count (distinct ext_project_id) "total projects" dbo.v_report_project inner bring together dbo.v_report_program on dbo.v_report_program.program_id = dbo.v_report_project.program_id project_status = 'active' , datediff (day, creation_date, getdate()) < 15 ;

the outcome is:

total projects 163

here want table like:

total projects | projects under 15 days | projects between 15 , 60 days | projects on 60 days 163 ?? ?? ??

how can find these different counts, @ same time?

you can utilize case limit particular count date range:

select count(distinct project_id) total , count(distinct case when datediff(day, creation_date, getdate()) < 6 project_id end) total_6day , count(distinct case when datediff(day, creation_date, getdate()) < 7 project_id end) total_7day , count(distinct case when datediff(day, creation_date, getdate()) < 42 project_id end) total_42day dbo.v_report_project proj bring together dbo.v_report_program prog on proj.program_id = prog.program_id project_status = 'active'

if no when matches , no else specified, case returns null. since count ignores null proper subtotals.

sql condition getdate

No comments:

Post a Comment