在SQL中添加具有不同条件的另一列

时间:2014-06-24 16:08:38

标签: sql conditional-statements getdate

我试图在同一个查询中查找有关我的数据的不同信息。我想根据不同的条件创建新列。这是我的表现在的样子

 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                     ??                           ??                             ??

如何同时找到这些不同的计数?

1 个答案:

答案 0 :(得分: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,因此您会获得正确的小计。