I have a table, let\'s call them table SUMMARYDATA
NIP NAME DEPARTMENT STATUSIN STATUSOUT TOTALLOSTTIME
------------
use conditional CASE
statement in a SUM()
select DEPARTMENT,
MONTH(STATUSIN),
YEAR(STATUSIN),
SUM (CASE WHEN TOTALLOSTTIME > '02:00:00') THEN 1 ELSE 0 END) AS RTOTALLOSTTIME
from SUMMARYDATA b
group by DEPARTMENT, MONTH(STATUSIN), YEAR(STATUSIN)
Try the following
select x.department
,x.month
,x.year
,count(case when x.sum_lost_time >'02:00:00' then NAME end) as RTOTALLOSTTIME
from (select MONTH(STATUSIN) as [month]
,YEAR(STATUSIN) as [year]
,NIP
,NAME
,DEPARTMENT
,convert(varchar,dateadd(second,sum(datediff(second,'00:00:00',cast(TOTALLOSTTIME as time))),0),108) as sum_lost_time
from SUMMARYDATA b
group by MONTH(STATUSIN)
,YEAR(STATUSIN)
,NIP
,NAME
,DEPARTMENT
)x
group by x.department
,x.month
,x.year
You are mainly just missing a WHERE
clause:
SELECT
DEPARTMENT,
MONTH(STATUSIN) AS MONTH,
YEAR(STATUSIN) AS YEAR,
SUM(DATEDIFF(second, '00:00:00', TOTALLOSTTIME)) AS sum_lost_time_in_sec
FROM SUMMARYDATA
WHERE
TOTALLOSTIME > '02:00:00'
GROUP BY
DEPARTMENT,
MONTH(STATUSIN),
YEAR(STATUSIN);