Question

I am attempting to do something I thought would be fairly simple in SQL Server but running into some road blocks. Basically I create two columns in a view and want to then use those columns to create a calculated column. I've read a few different questions but most of them involved cases or outside tables. Here is what I am attempting

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 .....

My [Email Total Response Time] and [Email Total Handled] create successfully, but the calculated column gives this error on execute

Msg 207, Level 16, State 1, Procedure PPM_OLH_NEW_MAIL_SESSION_CUBE, Line 22
Invalid column name 'Email Total Response Time'.
Msg 207, Level 16, State 1, Procedure PPM_OLH_NEW_MAIL_SESSION_CUBE, Line 22
Invalid column name 'Email Total Handled'.

Était-ce utile?

La solution

You can't refer directly to named items to create a new item within the same select.

So for example this will error :

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'.
*/

This will work instead (note you need the alias a) :

SELECT  val1
      , val2
      , val1 / val2
FROM    ( SELECT    20 AS val1
                  , 10 AS val2
        ) a

Or you could use a With clause to get the same result :

;
WITH    vals
          AS ( SELECT   20 AS val1
                      , 10 AS val2
             )
    SELECT  val1
          , val2
          , val1 / val2
    FROM    vals
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top