如何在计算后过滤掉某些值

时间:2018-01-17 06:41:10

标签: sql sql-server

我在SQL数据库中完成了一个Query,它从其他表中获取数据并将它们相加。那么我该如何过滤计算出的值WHERE Total_Hour < 12

我似乎无法识别Total_Hour

SELECT 
    r.Date,
    e.EmployeeID,
    e.GivenName,
    e.FamilyName,
    e.TeamID  ,
    e.ContactNo,
    r.ShiftID,
    COALESCE(s.Shift_Duration, 0) AS Shift_Duration,
    s.Shift_Timing,
    COALESCE(l.Duration_Off, 0) AS Duration_Off,
    COALESCE(o.OT_Duration, 0) AS OT_Duration,
    (COALESCE(s.Shift_Duration, 0) + COALESCE(o.OT_Duration, 0) - COALESCE(l.Duration_Off, 0)) AS Total_Hours
FROM 
    Employee e
    INNER JOIN
    Roster r ON  e.EmployeeID = r.EmployeeID 
    LEFT JOIN
    Leave l ON e.EmployeeID = l.EmployeeID AND r.Date = l.Date
    LEFT JOIN 
    Overtime o ON  e.EmployeeID = o.EmployeeID AND r.Date = o.Date
    INNER JOIN 
    ShiftType s ON r.ShiftID = s.ShiftID

    WHERE Total_Hours < '12'
ORDER BY Total_Hours ASC

2 个答案:

答案 0 :(得分:2)

只需将SELECT包裹在CTE或内部查询中,然后执行过滤器

;WITH CTE
AS
(
    SELECT 
       r.Date,
       e.EmployeeID,
       e.GivenName,
       e.FamilyName,
       e.TeamID  ,
       e.ContactNo,
       r.ShiftID,
       COALESCE(s.Shift_Duration, 0) AS Shift_Duration,
       s.Shift_Timing,
       COALESCE(l.Duration_Off, 0) AS Duration_Off,
       COALESCE(o.OT_Duration, 0) AS OT_Duration,
       (COALESCE(s.Shift_Duration, 0) + COALESCE(o.OT_Duration, 0) - COALESCE(l.Duration_Off, 0)) AS Total_Hours
    FROM 
       Employee e
       INNER JOIN
       Roster r ON  e.EmployeeID = r.EmployeeID 
       LEFT JOIN
       Leave l ON e.EmployeeID = l.EmployeeID AND r.Date = l.Date
       LEFT JOIN 
       Overtime o ON  e.EmployeeID = o.EmployeeID AND r.Date = o.Date
       INNER JOIN 
       ShiftType s ON r.ShiftID = s.ShiftID
)
SELECT
    *
    FROM CTE
    WHERE Total_Hours < '12'
ORDER BY Total_Hours ASC

或者像这样改变你的Where部分

WHERE (COALESCE(s.Shift_Duration, 0) + COALESCE(o.OT_Duration, 0) - COALESCE(l.Duration_Off, 0)) < '12'
ORDER BY (COALESCE(s.Shift_Duration, 0) + COALESCE(o.OT_Duration, 0) - COALESCE(l.Duration_Off, 0)) ASC

答案 1 :(得分:1)

您不能直接在where子句中使用它 但你可以用这个来代替

WHERE
(COALESCE(s.Shift_Duration, 0) + COALESCE(o.OT_Duration, 0) - COALESCE(l.Duration_Off, 0)) < '12'