在复杂的SQL查询中添加WHERE子句

时间:2016-05-29 11:24:48

标签: sql-server where

我想将ShowRoomId值传递给下面的查询。 Employees表格有ShowRoomId列。

我该怎么做?

我的SQL查询如下:

SELECT * 
FROM Employees A
OUTER APPLY (SELECT TOP 1 * 
             FROM EmployeeBasics B
             WHERE (A.EmployeeID = B.EmployeeID)
             ORDER BY B.BasicUpdateDate DESC) AS B
OUTER APPLY (
            SELECT C.EmployeeId , count(*) AS TotalAbsent 
            FROM EmployeeAbsents C  
            WHERE C.AbsentDate BETWEEN '2016-05-01' AND '2016-05-30' AND A.EmployeeID = C.EmployeeID
            GROUP BY C.EmployeeId
            ) AS C
OUTER APPLY (
            SELECT EmployeeId,
                SUM(CASE WHEN TransctionTypeId = 1 THEN Amount ELSE 0 END) AS Payment, 
                SUM(CASE WHEN TransctionTypeId = 2 THEN Amount ELSE 0 END) AS RecoverSalary, 
                SUM(CASE WHEN TransctionTypeId = 3 THEN Amount ELSE 0 END) AS RecoverCash
            FROM dbo.EmployeeAdvances D
            WHERE A.EmployeeID = D.EmployeeID
            GROUP BY EmployeeId
            ) AS D

2 个答案:

答案 0 :(得分:0)

最后只需使用WHERE子句,如下所示:

... YOUR SELECT ...
WHERE Col = ...YourCondition...

使用WITH关键字将当前SELECT - 语句保留在cte中。然后对它进行查询。

WITH cte AS
(
    ... YOUR SELECT ...
)

SELECT  *
FROM    cte
WHERE   Col = ...YourCondition...

您可以将SELECT - 语句添加到括号中,并使用别名命名。所以你也可以对它进行查询。

SELECT  *
FROM
(
    ... YOUR SELECT ...
) t

WHERE   t.Col = ...YourCondition...

答案 1 :(得分:0)

根据Giorgi Nakeuri的建议,我在声明的最后添加了WHERE条款。

它对我有用。修改后的代码在这里:

SELECT * 
FROM Employees A
OUTER APPLY (SELECT TOP 1 * 
             FROM EmployeeBasics B
             WHERE (A.EmployeeID = B.EmployeeID)
             ORDER BY B.BasicUpdateDate DESC) AS B
OUTER APPLY (
            SELECT C.EmployeeId , count(*) AS TotalAbsent 
            FROM EmployeeAbsents C  
            WHERE C.AbsentDate BETWEEN '2016-05-01' AND '2016-05-30' AND A.EmployeeID = C.EmployeeID
            GROUP BY C.EmployeeId
            ) AS C
OUTER APPLY (
            SELECT EmployeeId,
                SUM(CASE WHEN TransctionTypeId = 1 THEN Amount ELSE 0 END) AS Payment, 
                SUM(CASE WHEN TransctionTypeId = 2 THEN Amount ELSE 0 END) AS RecoverSalary, 
                SUM(CASE WHEN TransctionTypeId = 3 THEN Amount ELSE 0 END) AS RecoverCash
            FROM dbo.EmployeeAdvances D
            WHERE A.EmployeeID = D.EmployeeID
            GROUP BY EmployeeId
            ) AS D
WHERE A.ShowRoomId = 2