• The WHERE clause is processed before the SELECT statement, therefore any aliases assigned in SELECT statements are not available for their corresponding WHERE clauses. I have gotten around this by using a CROSS APPLY.

    SELECT

    TBU.businessunitidnameAS [BU Name],

    LEADS.statecodenameAS [Status],

    LEADS.statuscodeAS [Status Code],

    LEADS.accountidnameAS [Account Name],

    LEADS.parentcontactidnameAS [Parent Contact ID Name],

    LEADS.descriptionAS [Description],

    LEADS.createdonAS [Actual Close Date],

    d.[Days]

    FROM dbo.FilteredLeadAS LEADS

    INNER JOIN dbo.FilteredUserSettings AS TBU ON @BusinessUnitID = TBU.businessunitid

    CROSS APPLY(VALUES(DATEDIFF(day, '2015/01/01', LEADS.createdon))) AS d([Days])

    WHERE @BusinessUnitID= TBU.businessunitid

    AND @TheUser= LEADS.owneridname

    AND LEADS.statuscode= 3

    AND d.[Days] <= @ClosedWithin

    I would also recommend using square brackets rather than single quotes for quoting your field aliases. It helps to distinguish between data strings and field names.

    Drew

    J. Drew Allen
    Business Intelligence Analyst
    Philadelphia, PA