结合两个时间间隔查询

时间:2011-09-02 20:27:33

标签: sql sql-server sql-server-2008 tsql group-by

我有一个名为Call_Data的表,数据如下:

Arr_Date                   Interval    Han_Time   SL_Time  
2011-03-16 18:39:31.000    1830        1200       245
2011-03-16 20:06:03.000    2000        261        85
2011-03-31 00:35:42.000    0030        1900       400
2011-03-31 02:13:06.000    0200        2000       350

现在我想知道Han_time>的记录数量。 1800和SL_Time> 300

所以我写了两个查询来做到这一点:

  Select Arr_Date, Interval,
    Count(*) AS Han_Time_1800
    From Call_Data
    where Han_Time>1800
    Group by Arr_Date,Interval
    Order by Arr_Date,Interval

Select Arr_Date, Interval,
Count(*) AS SL_Time_300
From Call_Data
where SL_Time>300
Group by Arr_Date,Interval
Order by Arr_Date,Interval

有没有办法可以在一个查询中同时获取这两个值?

2 个答案:

答案 0 :(得分:2)

select Arr_Date,
       Interval,
       sum(case when Han_Time > 1800 then 1 else 0 end) as Han_Time_1800,
       sum(case when SL_Time > 300 then 1 else 0 end) as SL_Time_300
from Call_Data
where Han_Time > 1800 or 
      SL_Time > 300
group by Arr_Date, Interval
order by Arr_Date, Interval 

答案 1 :(得分:0)

这会有所帮助:

Select Arr_Date, Interval,
    Count(*) AS Han_Time_1800
    From Call_Data
    where Han_Time>1800
    and SL_Time>300
    Group by Arr_Date,Interval
    Order by Arr_Date,Interval