SQL Server: ORDER BY in subquery with UNION

后端 未结 4 1013
面向向阳花
面向向阳花 2020-12-11 15:43

i have two queries being combined with a UNION ALL1:

--Query 1
SELECT Flavor, Color
FROM Friends

 

<         


        
4条回答
  •  萌比男神i
    2020-12-11 16:28

    I'm suggesting to create a variable table in the format of the columns you want.

    1. run insert query from origin table into variable table for each table you which to join including all filters and sorting you want to apply.
    2. Return the Variable table

    Example:

    set nocount on
    DECLARE @temp_table TABLE(Flavor varchar(20), Color varchar(20))
        
        insert into @temp_table (Flavor,Color)
        /*Apply select query #1 with all filters, joins and sorting */
        SELECT Flavor,Color   FROM Strangers  ORDER BY Wavelength DESC
        
        insert into @temp_table (Flavor,Color)
        /*Apply select query #2 with all filters, joins and sorting */
        SELECT Flavor, Color FROM Friends
        
        /*Return the results pushed into @variable table */
        select * from @temp_table
    

提交回复
热议问题