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

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

提交回复
热议问题