如何为聚合添加Case语句

时间:2013-12-21 19:06:10

标签: sql sql-server tsql sql-server-2005

我有一个查询,获取时钟和休息时间异常。如果有人不休息,休息时间是负数。我需要报告“BreakTime”,但是我需要将负分钟分钟更改为“0”,否则报告分钟。

我的查询是:

SELECT lEmployeeID, sFirstName, sLastName, 
       TotalHours, BreakTime, SkippedBreak, ShortBreak
FROM (
    SELECT lEmployeeID, sFirstName, sLastName, 
        SUM(TotalHours) AS TotalHours, 
        DATEDIFF(mi, MIN(dtTimeOut), MAX(dtTimeIn)) AS BreakTime, 
        CASE WHEN SUM(ftc.TotalHours) > 6 
              AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 0 
             THEN 1 
             ELSE 0 
        END AS SkippedBreak, 
        CASE WHEN DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) < 30 
              AND DATEDIFF(mi, MIN(ftc.dtTimeOut), MAX(ftc.dtTimeIn)) > 0 
             THEN 1 
             ELSE 0 
        END AS ShortBreak
    FROM dbo.fTimeCard(@StartDate, @EndDate, @DeptList, 
                       @iActive, @EmployeeList) AS ftc
    WHERE (DID IS NOT NULL) 
       OR (DID IS NOT NULL) 
      AND (dtTimeOut IS NULL)
    GROUP BY lEmployeeID, sFirstName, sLastName
) AS sub
WHERE (SkippedBreak = 1) 
   OR (ShortBreak = 1)

现在我的输出看起来像这样:

Bob Bibby   6.03    -362
Rob thomas  10.53   -632
Bret smith  7.6 17
Ron blah    8.1 25

我需要将负的休息时间分钟设为“0”

1 个答案:

答案 0 :(得分:1)

将查询包装在使用CASE来处理负聚合值的外部查询中:

SELECT
    lEmployeeID, sFirstName, sLastName, TotalHours, 
    CASE WHEN BreakTime < 0 THEN 0 ELSE BreakTime END AS BreakTime,
    SkippedBreak, ShortBreak
FROM (
    <your current query>
) t