在Where子句中使用Inner Select值

时间:2014-10-13 15:30:55

标签: sql sql-server tsql stored-procedures sqlxml

我有一个SQL查询,我试图在外部value子句中使用子选项where

SELECT   count(A.[processID]) AS total,
         B.[process] AS processName,
         (SELECT   TOP 1 LocationDesc
          FROM     dbo.EmployeeTable_Historical AS D
          WHERE    C.leaver = D.QID
          ORDER BY meta_logDate DESC)
FROM     dbo.attritionDataPrevention AS A
         INNER JOIN
         attritionProcesses AS B
         ON A.[processID] = B.[processID]
         INNER JOIN
         dbo.attritionData AS C
         ON A.[recordID] = C.recordID
WHERE    D.[locationDesc] IN (SELECT location
                              FROM   @table)
         AND YEAR(C.[leaveDate]) = @year
GROUP BY B.[processID]
ORDER BY total DESC
FOR      XML PATH ('type'), TYPE, ELEMENTS, ROOT ('root');

在我的主WHERE子句中,它说不能BIND WHERE D.[locationDesc]S别名位于子查询中,因此我不太清楚如何使用其值。

更新

根据建议,我将代码更改为以下内容:

SELECT   count(A.[processID]) AS total,
                         B.[process] AS processName
FROM     dbo.attritionDataPrevention AS A
         INNER JOIN
         attritionProcesses AS B
         ON A.[processID] = B.[processID]
         INNER JOIN 
         dbo.attritionData AS C
         ON A.recordID = C.recordID,
         (
             SELECT TOP 1 D.LocationDesc
             FROM dbo.EmployeeTable_Historical AS D
             WHERE C.leaver = D.QID
             ORDER BY D.[meta_logDate] DESC
         ) AS D
WHERE    D.locationDesc IN (SELECT location FROM @table)
         AND YEAR(C.[leaveDate]) = @year
GROUP BY B.[process]
ORDER BY total DESC
FOR      XML PATH ('type'), TYPE, ELEMENTS, ROOT ('root');

现在唯一的问题是WHERE C.leaver不会绑定到内连接。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT   count(A.[processID]) Over (Partition by B.[processID]) AS total,
         B.[process] AS processName,
         (SELECT   TOP 1 LocationDesc
          FROM     dbo.EmployeeTable_Historical AS D
          WHERE    C.leaver = D.QID
          AND D.[locationDesc] IN (SELECT location FROM @table)
          ORDER BY meta_logDate DESC)
FROM     dbo.attritionDataPrevention AS A
         INNER JOIN
         attritionProcesses AS B
         ON A.[processID] = B.[processID]
         INNER JOIN
         dbo.attritionData AS C
         ON A.[recordID] = C.recordID
WHERE    YEAR(C.[leaveDate]) = @year
ORDER BY total DESC
FOR      XML PATH ('type'), TYPE, ELEMENTS, ROOT ('root');