title: Sort with Insert statement
body: <p>I'm calculating a linear regression in SQL and need to preserve the Sort order in the #regression_data table.</p>
  
  <p>I'm creating a time series regression and the row_number() is creating the count for X values.  The regression needs to maintain the proper sort order to function properly.</p>
  
  <p>The following code works properly when I don't insert into a temp table because I have the ability to sort.  Even if I use don't create a Temp Table I don't believe I sort within a derived query.</p>
  
  <p>if object_id('tempdb..#regression_data') is not null begin drop table #regression_data end</p>
  
  <pre><code>Select CAST(ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as INT) 'x', CAST([Pax] as INT) 'y', *
  
  --into #regression_data
  from #TBB_Temp
  </code></pre>
  
  <p>´   Order by [Depart Year],[Booking Year], [Sorter]</p>