我正在尝试做一些我认为在SQL Server中相当简单但遇到一些障碍的事情。基本上我在视图中创建了两列,然后想要使用这些列来创建计算列。我已经阅读了几个不同的问题,但大多数都涉及案例或外部表格。这是我正在尝试的
CREATE VIEW [dbo].[VIEW_NAME]
AS
SELECT
,DATEDIFF (SECOND, (CAST(a.begintime as datetime)), (CAST (a.endtime as datetime))) AS [Email Total Response Time]
,1 AS [Email Total Handled]
,[Email Total Response Time] / COUNT([Email Total Handled]) AS [Avg Email Response Time]
FROM .....
我的[Email Total Response Time]
和[Email Total Handled]
创建成功,但计算列在执行时出现此错误
消息207,级别16,状态1,过程PPM_OLH_NEW_MAIL_SESSION_CUBE,第22行
列名称“电子邮件总响应时间”无效 消息207,级别16,状态1,过程PPM_OLH_NEW_MAIL_SESSION_CUBE,行22 列名称“电子邮件总数已处理”无效。
答案 0 :(得分:3)
您不能直接引用命名项目来在同一个选择中创建新项目。
例如,这将是错误:
SELECT 20 AS val1
, 10 AS val2
, val1 / val2
/*
Msg 207, Level 16, State 1, Line 4 Invalid column name 'val1'.
Msg 207, Level 16, State 1, Line 4 Invalid column name 'val2'.
*/
这将起作用(注意你需要别名a):
SELECT val1
, val2
, val1 / val2
FROM ( SELECT 20 AS val1
, 10 AS val2
) a
或者您可以使用With子句来获得相同的结果:
;
WITH vals
AS ( SELECT 20 AS val1
, 10 AS val2
)
SELECT val1
, val2
, val1 / val2
FROM vals