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

后端 未结 4 2139
无人共我
无人共我 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
    

提交回复
热议问题