简体   繁体   中英

How to reference TSQL calculated field from outer query in subquery

Not sure how to code the following in T-SQL:

Select 
    RunDate, 
    Lead(RunDate) Over(Order By Rundate) NextRunDate,
    (Select count(*) 
     From DetailTable
     Where DetailTable.EventDate <= NextRunDate) as Cnt
From   
    RunDates

The use of NextRunDate in the subquery throws an

Invalid column name

error, which makes sense. But how to reference that outer variable? Thanks!

You can nest your query leaving out the subquery in another query, that then includes the subquery.

SELECT x.rundate,
       (SELECT count(*)
               FROM detailtable d
               WHERE d.eventdate <= x.nextrundate) cnt
       FROM (SELECT r.rundate, 
                    lead(r.rundate) OVER (ORDER BY r.rundate) nextrundate
                    FROM rundates r) x;

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