2014-06-24 93 views
1

我試圖在同一個查詢中查找有關我的數據的不同信息。我想根據不同的條件創建新的列。這裏是我的表看起來像現在在SQL中添加具有不同條件的另一列

SELECT COUNT (distinct ext_project_id) as "Total Projects" 
    FROM dbo.v_report_project 
    INNER JOIN dbo.v_report_program 
    ON dbo.v_report_program.program_id = dbo.v_report_project.program_id 
    WHERE project_status = 'Active' 
    AND datediff (day, creation_date, getdate()) < 15 ; 

的結果是:

Total Projects 
163 

這是我希望我的表看起來像:

Total Projects | Projects Under 15 Days | Projects Between 15 and 60 Days | Projects  Over 60 Days 
163      ??       ??        ?? 

我怎樣才能找到這些不同的計數,所有在同一時間?

回答

0

您可以使用case到特定count限制在特定日期範圍:

select count(distinct project_id) as total 
,  count(distinct case 
      when datediff(day, creation_date, getdate()) < 6 
      then project_id end) as total_6day 
,  count(distinct case 
      when datediff(day, creation_date, getdate()) < 7 
      then project_id end) as total_7day 
,  count(distinct case 
      when datediff(day, creation_date, getdate()) < 42 
      then project_id end) as total_42day 
from dbo.v_report_project proj 
join dbo.v_report_program prog 
on  proj.program_id = prog.program_id 
where project_status = 'Active' 

如果沒有指定when比賽和沒有else,一個case回報null。由於count忽略了null,您會得到適當的小計。

+0

完美的工作!謝謝一堆 –

相關問題