2011-07-15 84 views
1

我需要從子查詢中的外部查詢中訪問別名,如此代碼。除非它不起作用。有沒有辦法做到這一點? 我的目標是爲每個OwnerIdName創建這些聚合函數,這是我能想到的唯一方法。 我在SQL Server 2008工作訪問子查詢中的別名

感謝

SELECT Incident.OwnerIdName as OIN 
    ,(SELECT COUNT(*) 
    FROM Incident 
    WHERE CreatedOn BETWEEN '2011/1/1' AND '2011/1/31' 
    AND Incident.OwnerIdName = OIN) as CasesOpened 
    ,(SELECT COUNT(*) 
    FROM IncidentResolution 
    WHERE ActualEnd BETWEEN '2011/1/1' AND '2011/1/31' 
      AND Incident.OwnerIdName = OIN) as CasesClosed 
FROM Incident 

回答

3

你不能直接使用的列名..?如..

SELECT Inc.OwnerIdName as OIN 
    ,(SELECT COUNT(*) 
    FROM Incident 
    WHERE CreatedOn BETWEEN '2011/1/1' AND '2011/1/31' 
    AND Incident.OwnerIdName = Inc.OwnerIdName) as CasesOpened 
    ,(SELECT COUNT(*) 
    FROM IncidentResolution 
    WHERE ActualEnd BETWEEN '2011/1/1' AND '2011/1/31' 
      AND Incident.OwnerIdName = Inc.OwnerIdName) as CasesClosed 
FROM Incident Inc 

如果您想直接使用別名,你將不得不做,早在你的查詢,然後將它用於所有的標量子查詢..

SELECT INC.OIN 
    ,(SELECT COUNT(*) 
    FROM Incident 
    WHERE CreatedOn BETWEEN '2011/1/1' AND '2011/1/31' 
    AND Incident.OwnerIdName = INC.OIN) as CasesOpened 
    ,(SELECT COUNT(*) 
    FROM IncidentResolution 
    WHERE ActualEnd BETWEEN '2011/1/1' AND '2011/1/31' 
      AND Incident.OwnerIdName = INC.OIN) as CasesClosed 
from 
(Select OwnerIdName OIN 
    FROM Incident) INc 
+0

謝謝。我沒有想到這一點。 :) – Aaron

1

試試這個(適用於SQL = 2005):

WITH 
    CreatedQry AS 
    (
     SELECT OwnerIdName, COUNT(1) AS CreatedCount 
      FROM Incident 
     WHERE CreatedOn BETWEEN '2011/1/1' AND '2011/1/31' 
    ), 
    EndQry AS 
    (
     SELECT OwnerIdName, COUNT(1) AS EndCount 
      FROM IncidentResolution 
     WHERE ActualEnd BETWEEN '2011/1/1' AND '2011/1/31' 
    ) 
    SELECT CreatedQry.OwnerIdName, CreatedCount, EndCount 
     FROM CreatedQry LEFT JOIN EndQry 
     ON CreatedQry.OwnerIdName = EndQry.OwnerIdName