在子句中使用SQL SERVER计算天数

时间:2017-03-31 17:19:11

标签: sql-server

我有桌子

1        2013-10-01 08:21        Null               Null        Null
1        2013-10-01 14:30        Null               Null        Null
2        2013-10-01 08:31        Null                Lt         Null
2        2013-10-01 14:31         EO                Null        Null
3        2013-10-01 14:30         EO                Null       Ab here

此表是此查询的结果

 SELECT m.ID,L.Log_D,W.Sat,L.C,
   (CASE WHEN convert(time,L.Log_D)>'08:31:00' and convert(time,L.Log_D)<'10:30:00' and L.C =1  then 'Lt'end )as Late,
     (CASE WHEN convert(time,L.Log_D)<'13:30:00'  and L.C =2  then 'Ab'end )as EarlyOut,
     (CASE WHEN DATENAME(DAY, day( L.Log_D)) =2 THEN 'Ab'  END) as Counte
   from WorkPeriod W,LogT L,MinimumInfoT m  where  day(L.Log_D) =1 
   and month(L.Log_D) =10
   and year(L.Log_D) =2013 
   and W.id=54 
   and m.Branch_ID=35 
   and L.C in(1,2) 
   and M.ID =L.EmpId 
   and W.id =m.W_Period 
   group by m.ID,L.Log_D,W.Sat,L.C 
   order by m.ID

当每天的点数少于2时,我需要将缺席列显示为'Ab',这样可能会有任何帮助

1 个答案:

答案 0 :(得分:1)

您可以使用窗口函数执行此操作:

CASE WHEN COUNT(*) OVER (PARTITION BY m.ID) < 2 THEN 'ab' ELSE NULL END as Counte

这将获得每个不同m.ID的记录数。如果当前m.ID的计数小于2,则会吐出ab