Count summary records per month with conditional SQL

后端 未结 3 2074
无人共我
无人共我 2021-01-29 03:37

I have a table, let\'s call them table SUMMARYDATA

NIP  NAME   DEPARTMENT       STATUSIN           STATUSOUT             TOTALLOSTTIME 
------------         


        
相关标签:
3条回答
  • 2021-01-29 04:02

    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)
    
    0 讨论(0)
  • 2021-01-29 04:06

    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        
    
    0 讨论(0)
  • 2021-01-29 04:10

    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);
    
    0 讨论(0)
提交回复
热议问题