简体   繁体   中英

How can I use a created column as a filter

I am trying to figure a work around for this query I am writing in SQL Server.

I need to be able to use the results from the CASE statement in the DateDiff function.

  • If the encounter end date is null then I want to use the encounter begin date for the date diff calculation.

  • If the encounter end date is not null then I want to use the encounter end date for the date diff calculation.

However, I keep getting an "invalid column name" error when I put the dateofservice in the datediff function.

This is my code:

Select 
    e.encounterid,
    Case 
        when e.encounterenddate = null
            then e.encounterbegindate
        else e.encounterenddate
    end as dateofservice,
    rf.submissiondate,
    datediff(day, dateofservice, rf.submissiondate) as lagtime,
    rf.healthplancode,
    rf.transactiontypeid
from 
    udt_encounter as E
join 
    udt_receivedfile as RF on e.receivedfileid = rf.receivedfileid
where 
    rf.healthplancode = '00'
    and rf.transactiontypeid = 1
    and rf.submissiondate between '2020-01-01' and '2020-06-30'
order by 
    encounter.id asc

You do not even need CASE , COALESCE will do it.
Since this is quite short I would stick with simply repeating the expression:

SELECT 
    e.encounterid,
    COALESCE(e.encounterenddate, e.encounterbegindate) AS dateofservice
    ,rf.submissiondate
    ,datediff(day, COALESCE(e.encounterenddate, e.encounterbegindate), rf.submissiondate) AS lagtime
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM