为什么datepart提取小时不工作以防万一?

时间:2014-10-30 12:38:38

标签: sql-server-2008

  

大家好,datepart中的case when没有效果。我试过这个...
  这有效:

select status_name ,count(pk_lead_id) as leads where lm.lead_created_date between @sDate and @eDate and datepart(hh,lead_created_date) in (9,10,11,12,13,14,15,16,17,18,19) and datepart(hh,lead_created_date) in (20,21,22,23,0,1,2,3,4,5,6,7,8) from lead_master group by status_name

  

但这并没有给出正确的输出:

select status_name ,count(pk_lead_id) as leads --'9am to 8pm' and '8pm to 9am' ,count(case when cast(right(left(lead_created_date,13),2) as int) in (9,10,11,12,13,14,15,16,17,18,19)then 1 else 0 end)as morning ,count(case when cast(right(left(lead_created_date,13),2) as int) in (20,21,22,23,0,1,2,3,4,5,6,7,8)then 1 else 0 end)as night from lead_master group by status_name

  

我需要在datepart ...

中查询case when条件的作用

1 个答案:

答案 0 :(得分:1)

为什么要在日期时间列上应用RIGHTLEFT

case when cast(right(left(lead_created_date,13),2) as int) in (9,10,11,12,13,14,15,16,17,18,19)then 1 else 0 end

将您的查询更改为:

select status_name
       ,count(pk_lead_id) as leads --'9am to 8pm' and '8pm to 9am'
       ,sum(case when datepart(hh,lead_created_date) in (9,10,11,12,13,14,15,16,17,18,19) then 1 else 0 end)as morning 
       ,sum(case when datepart(hh,lead_created_date) in (20,21,22,23,0,1,2,3,4,5,6,7,8) then 1 else 0 end)as night
from lead_master group by status_name