SQL - 使用子选择分组?

时间:2012-08-01 08:37:40

标签: sql

我有以下查询:

SELECT COUNT(DATEPART(hh, CallStart)), DATEPART(hh, CallStart) as 'Hour'
  FROM PhoneSystemLog 
 WHERE MONTH(CallStart) = @Month and YEAR(CallStart) = @Year 
 GROUP BY DATEPART(hh, CallStart)

这很好,它会将每小时拨打的电话数量分组,但我想要做的是然后在上午12点到早上7点之间进行群组通话,下午6点到12点之间进行群组通话,因为没有许多人都是在这些时候制作的,因此在这几个小时内每小时拨打一次电话似乎毫无意义(因为他们已经没有工作时间)。这可能吗?

2 个答案:

答案 0 :(得分:4)

您可以使用case将小时翻译为句点:

select  Period
,       count(*) as Calls
from    (
        select  case 
                when datepart(hh, CallStart) between 0 and 7 then '1-7'
                when datepart(hh, CallStart) between 18 and 23 then '18-24'
                else cast(datepart(hh, CallStart) as varchar(2))
                end as Period
        from    PhoneSystemLog
        where   MONTH(CallStart) = @Month 
                and YEAR(CallStart) = @Year 
        ) as SubQueryAlias
group by
        Period

答案 1 :(得分:0)

尝试这样的事情

select count(DATEPART(hh, CallStart)), 
    CASE 
    when DATEPART(hh, callstart) between 0 to 7 then '12:00AM-7AM'
    when DATEPART(hh, callstart) between 18 to 23 then '06PM-12AM'
    END
as 'hour' from PhoneSystemLog  
where MONTH(callstart) = @Month and YEAR(callstart) = @Year  
group by 
    CASE 
    when DATEPART(hh, callstart) between 0 to 7 then '12:00AM-7AM'
    when DATEPART(hh, callstart) between 18 to 23 then '06PM-12AM'
    END