在子查询中访问别名

时间:2011-07-15 21:36:37

标签: sql sql-server tsql

我需要从子查询中的外部查询访问别名,就像这段代码一样。除非它不起作用。有没有办法做到这一点? 我的目标是为每个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

2 个答案:

答案 0 :(得分: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

如果要直接使用Alias,则必须在查询的早期执行此操作,然后将其用于所有标量子查询。

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 

答案 1 :(得分: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