title: Iterate through derived value from temp table so it value can be used it a where condition using for loop
body: <p>I can get the total for each of the items from a derived table like so:</p>
  
  <pre><code>declare @laneNum int
  declare @startDate date = '2019-02-07'
  declare @class int = 1
  declare @id int 
  
  if OBJECT_ID('tempdb..#tempLaneNumber') IS NOT NULL
  drop table [#tempLaneNumber]
  
  create table #tempLaneNumber
  (
      LANE_NUMBER INT NULL
  )    
  
  INSERT INTO #tempLaneNumber (LANE_NUMBER)
    SELECT DISTINCT EXIT_LANE
    FROM [dbo].[TOLL] 
    ORDER BY EXIT_LANE DESC
  
  select l.LANE_NUMBER, COUNT(*)
  from [dbo].[TOLL] t
  inner join  #tempLaneNumber l on t.EXIT_LANE = l.LANE_NUMBER
  where convert(date, TRXN_DTIME) = @startDate 
  GROUP BY l.LANE_NUMBER
  </code></pre>
  
  <p>But what I need now is to iterate through each of the derived values so I can use it in a statement where each result can be placed in a variable. This is what I get in my current code...</p>
  
  <p><a href="https://i.stack.imgur.com/hprAc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hprAc.png" alt="enter image description here"></a></p>
  
  <p>I need to put LANE_NUMBER 4 into x4 variable and LANE_NUMBER 6 into x6 variable and so forth. How do I get to it?</p>
  
  <p><strong>EDIT</strong></p>
  
  <pre><code>declare @laneNum int
  declare @startDate date = '2019-02-07'
  declare @class int = 1
  declare @id int 
  
  if OBJECT_ID('tempdb..#tempLaneNumber') IS NOT NULL
  drop table [#tempLaneNumber]
  
  create table #tempLaneNumber
  (
      LANE_NUMBER INT NULL
  )
  
  
  INSERT INTO #tempLaneNumber (LANE_NUMBER)
  SELECT DISTINCT EXIT_LANE
  FROM [dbo].[TOLL] 
  ORDER BY EXIT_LANE DESC
  
  
  ;WITH CTE AS
  (
      select l.LANE_NUMBER, COUNT(*) CT
      from [dbo].[TOLL] t
      inner join  #tempLaneNumber l on t.EXIT_LANE = l.LANE_NUMBER
      where convert(date, TRXN_DTIME) = @startDate 
      GROUP BY l.LANE_NUMBER
  )
  SELECT * FROM CTE where LANE_NUMBER = 4
  </code></pre>
  
  <p>This is about right but the problem is I would need to hardcode the value "4" or "6" or "7". This sample has 4 results so it's okay. but what if I have 10 or more?</p>