ORDER BY with a UNION of disparate datasets (T-SQL)

后端 未结 4 2028
无人共我
无人共我 2021-02-19 04:41

I have a query that UNION\'s two somewhat similar datasets, but they both have some columns that are not present in the other (i.e., the columns have NULL values in

相关标签:
4条回答
  • 2021-02-19 04:59

    You should use UNION ALL instead of UNION to save the cost of duplicate checking.

    SELECT *
    FROM
    (
    SELECT t1.ID, t1.Cat, t1.Price, NULL as Name, NULL as Abbrv FROM t1
    UNION ALL
    SELECT t2.ID, NULL as Cat, NULL as Price, t2.Name, t2.Abbrv FROM t2
    ) as sub
    ORDER BY
      ID,
      CASE WHEN Price is not null THEN 1 ELSE 2 END,
      Price DESC,
      CASE WHEN Abbrv is not null THEN 1 ELSE 2 END,
      Abbrv ASC
    
    0 讨论(0)
  • 2021-02-19 05:09

    A quick solution would be to do 2 inserts into a temp table or a table variable and as part of insert into the temp table you can set a flag column to help with sorting and then order by that flag column.

    0 讨论(0)
  • 2021-02-19 05:13

    Off the top of my head i would say the worst case scenario is you create a temporary table with all the fields do an INSERT INTO the temp table from both T1 & T2 then SELECT from the temp table with an order by.

    ie. Create a temp table (eg. #temp) with fields Id, Cat, Price, Name, Abbrv, and then:

    SELECT Id, Cat, Price, null, null INTO #temp FROM T1
    SELECT Id, null, null, Name, Abbrv INTO #temp FROM T2
    SELECT * FROM #temp ORDER BY Id, Price DESC, Abbrv ASC
    

    NB: I'm not 100% sure on the null syntax from the inserts but i think it will work.

    EDIT: Added ordering by Price & Abbrv after id... if Id doesn't link T1 & T2 then what does?

    0 讨论(0)
  • 2021-02-19 05:16
    Select ID, Cat, Price, Name, Abbrv
    From
    (SELECT t1.ID, t1.Cat, t1.Price, t1.Price AS SortPrice, NULL as Name, NULL as Abbrv 
    FROM t1
    UNION
    SELECT t2.ID, NULL as Cat, NULL as Price, t1.Price as SortPrice, t2.Name, t2.Abbrv 
       FROM t2
       inner join t1 on t2.id = t1.id
    ) t3
    ORDER BY SortPrice DESC, Abbrv ASC
    

    Somehow you have to know the data in table 2 are linked to table 1 and share the price. Since the Null in abbrv will come first, there is no need to create a SortAbbrv column.

    0 讨论(0)
提交回复
热议问题