在SQL 2008中使用基于查询结果的Count

时间:2014-08-26 09:39:52

标签: sql-server-2008

嗨我有一个表格,我想要计算,并通过减去每个列中的值来对结果进行分类。

StartDate          EndDate
09:45              10:30
10:00              12:00
10:30              11:00
11:00              17:00
11:15              12:00

在上表中,我想知道在不到2小时内完成了多少次,在2小时内完成了多少次。 结果如下:

Below 2hours       2hours and Above
3                    2

2 个答案:

答案 0 :(得分:0)

select case when DATEDIFF(HH,start_time,end_time) <1 then 'below one hour'
   when DATEDIFF(HH,start_time,end_time) <2 then 'below 2 hour'
    when DATEDIFF(HH,start_time,end_time) <3 then 'below 3 hour'
     when DATEDIFF(HH,start_time,end_time) <4 then 'below 4 hour'
      when DATEDIFF(HH,start_time,end_time) <5 then 'below 5 hour'
      else 'above 5'
      end  from WU_DATAMART_ETL_LOG

请尝试此代码

答案 1 :(得分:0)

您可以使用上面的select语句,但只需添加计数功能,如下所示

select
    count(Below_2hours) AS Below_2hours,
    count(2hours_and_Above) AS 2hours_and_Above from
    (
    select
        case
            when DATEDIFF(HH,start_time,end_time) <2 then 'Below_2hours'
            when DATEDIFF(HH,start_time,end_time) >2 then '2hours_and_Above'
        end  from Table_Name ) AS A