select campaign
,ISNULL(sum(cast (HandleTime as bigint)), 0) handleTime
,(select Contacts from [View_ContactsByCampaign] Con where Con.Campaign = C.Campaign) Contacts
, ContactPerTime = Contacts / handleTime
from call C
group by campaign
我在计算ContactPerTime值时遇到问题。我收到“无效的列名'联系人'。”和“无效的列名'handleTime'”错误。是否可以使用这些值进行计算?
答案 0 :(得分:1)
您不能通过别名引用SELECT
语句中的其他列。如果你再次需要表达式,你需要重复所述表达式:
SELECT campaign,
ISNULL(SUM(CAST (HandleTime AS bigint)), 0) AS handleTime,
(SELECT Contacts
FROM [View_ContactsByCampaign] Con
WHERE Con.Campaign = C.Campaign) AS Contacts,
(SELECT Contacts
FROM [View_ContactsByCampaign] Con
WHERE Con.Campaign = C.Campaign) / handleTime AS ContactPerTime
FROM [CALL] C
GROUP BY campaign;
但是,正如您所拥有的是子查询,您最好使用APPLY
。可能类似::
SELECT campaign,
ISNULL(SUM(CAST (HandleTime AS bigint)), 0) AS handleTime,
Con.Contacts
Con.Contacts / handleTime AS ContactPerTime
FROM [CALL] C
CROSS APPLY(SELECT Contacts
FROM [View_ContactsByCampaign] ca
WHERE ca.Campaign = C.Campaign) Con
--Considering that Contacts was returned from a subquery, it's likely a "safe"
--assumption it will return 1 row. If it didn't, then your previous query
--would have errored anyway.
GROUP BY campaign, Contacts;
供参考,请查看Logical Processing Order of the SELECT
statement:其中说明:
相反,因为
SELECT
子句是步骤8,所以任何列别名或 该子句中定义的派生列不能被引用 前面的条款。但是,它们可以通过后续引用 条款,例如ORDER BY
子句。
ORDER BY
实际上是唯一可以在语句的同一部分通过别名引用列的位置。