title: PowerShell multiple SQL queries, Cannot use Order by in each query
body: <p>I'm using PowerShell to run a SQL query consisting of multiple <code>SELECT DISTINCT</code> statements.  Using <code>UNION ALL</code> to join these results into one result.</p>
  
  <p>I was wondering if it was possible to use <code>Order By</code> in each Select statement.</p>
  
  <p>I currently have the following, only showing Monday,Tuesday but it should be easy to follow along for the remaining days.  If I add <code>ORDER BY</code> at the last SELECT statement, the results are ordered correctly but taken out of the DayOfWeek sort.</p>
  
  <p>I'm just not sure how to use any of the examples I've found, which use the <code>()</code> to create a nested SELECT statement or SubQuery.</p>
  
  <p>-edit, forgot to mention I'm looking to OrderBy the <code>[RebootTime]</code> column for each DayOfWeek query.</p>
  
  <pre class="lang-psh prettyprint-override"><code>$SQLServer = "ServerNameHere"
  $SQLDBName = "DBNameHere"
  $SqlQuery = @'
  SELECT DISTINCT dbo.server AS [Server], dbo.rack AS [Rack], dbo.Environment AS [Environment], dbo.monday AS [RebootTime], dbo.schedule AS [Schedule]
  FROM SomeTable
  INNER JOIN SubTable
   ON dbo.Item = dbo.SpecID
  WHERE dbo.monday = 1
  AND (dbo.Environment = 'Prod' OR  dbo.Environment = 'Cert' OR dbo.Environment = 'Test')
  AND (dbo.schedule = 'Weekly' OR dbo.schedule = 'SCCM - Weekly' OR dbo.schedule = 'Monthly' OR dbo.schedule = 'SCCM - Monthly')
  AND dbo.Group = 'MyGroup'
  AND dbo.object = 'Server'
   UNION ALL
  SELECT null, null, null, null, null
   UNION ALL
  SELECT 'Tuesday', null, null, null, null
   UNION ALL
  SELECT 'Server', 'Rack', 'Environment', 'RebootTime', 'Schedule'
   UNION ALL
  SELECT DISTINCT dbo.server AS [Server], dbo.rack AS [Rack], dbo.Environment AS [Environment], dbo.tuesday AS [RebootTime], dbo.schedule AS [Schedule]
  WHERE dbo.tuesday = 1
  AND (dbo.Environment = 'Prod' OR  dbo.Environment = 'Cert' OR dbo.Environment = 'Test')
  AND (dbo.schedule = 'Weekly' OR dbo.schedule = 'SCCM - Weekly' OR dbo.schedule = 'Monthly' OR dbo.schedule = 'SCCM - Monthly')
  AND dbo.Group = 'MyGroup'
  AND dbo.object = 'Server'
  '@
   $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
   $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
   $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
   $SqlCmd.CommandText = $SqlQuery
   $SqlCmd.Connection = $SqlConnection
   $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
   $SqlAdapter.SelectCommand = $SqlCmd
   $DataSet = New-Object System.Data.DataSet
   $SqlAdapter.Fill($DataSet)
   $SqlConnection.Close()
  $DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path D:\Scripts\Output.csv
  Invoke-Item -Path d:\Scripts\Output.csv
  </code></pre>