我需要从子查询中的外部查询来访问别名,比如这个代码。除非不起作用。有没有办法做到这一点?我的目标是为每一个OwnerIdName创建这些聚合函数是我唯一能想到的方法。我正在使用它SQLServer 2008。, i# O8 c" g- N6 U$ N- Q( L
谢谢 2 @' U' d: ?9 l8 O. r& FSELECT Incident.OwnerIdName as OIN ,(SELECT COUNT(*) FROM Incident WHERE CreatedOn BETWEEN AND '2011/1/31' AND Incident.OwnerIdName = OIN ) as CasesOpened ,(SELECT COUNT(*) FROM IncidentResolution WHERE ActualEnd BETWEEN AND '2011/1/31' AND Incident.OwnerIdName = OIN ) as CasesClosedFROM Incident 8 R9 @6 T0 E3 @' |( A7 [解决方案: - E$ q- k5 D) G, ]2 W1 r 你不能直接使用列名吗?.. + P) ^) l+ {( b8 [: r" t' USELECT Inc.OwnerIdName as OIN ,(SELECT COUNT(*) FROM Incident WHERE CreatedOn BETWEEN AND AND Incident.OwnerIdName = Inc.OwnerIdName ) as CasesOpened ,(SELECT COUNT(*) FROM IncidentResolution WHERE ActualEnd BETWEEN AND AND Incident.OwnerIdName = Inc.OwnerIdName ) as CasesClosedFROM Incident Inc若要直接使用Alias,此操作必须在查询的早期进行,然后用于所有标量子查询。 0 u) z) G# l; b8 y5 ZSELECT INC.OIN ,(SELECT COUNT(*) FROM Incident WHERE CreatedOn BETWEEN AND AND Incident.OwnerIdName = INC.OIN ) as CasesOpened ,(SELECT COUNT(*) FROM IncidentResolution WHERE ActualEnd BETWEEN AND AND Incident.OwnerIdName = INC.OIN ) as CasesClosedfrom (Select OwnerIdName OIN FROM Incident) INc