我有一个查询,UNION
的两个数据集有些相似,但它们都有一些在另一个数据集中不存在的列(即,这些列在结果 中具有 NULL 值)联合
。)
问题是,我需要使用仅存在于一个或另一组中的那些列来ORDER
结果数据,以便以软件端友好的格式获取数据。
例如:Table1 具有字段ID、Cat、Price
。 Table2 具有字段ID、名称、缩写
。 ID
字段在两个表之间是通用的。
我的查询看起来像这样:
SELECT t1.ID, t1.Cat, t1.Price, NULL as Name, NULL as Abbrv FROM t1
UNION
SELECT t2.ID, NULL as Cat, NULL as Price, t2.Name, t2.Abbrv FROM t2
ORDER BY Price DESC, Abbrv ASC
ORDER BY
是我陷入困境的地方。数据如下所示:
100 Balls 1.53
200 Bubbles 1.24
100 RedBall 101RB
100 BlueBall 102BB
200 RedWand 201RW
200 BlueWand 202BW
...但我希望它看起来像这样:
100 Balls 1.53
100 RedBall 101RB
100 BlueBall 102BB
200 Bubbles 1.24
200 RedWand 201RW
200 BlueWand 202BW
我希望这可以在 T-SQL 中完成。
最佳答案
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
您必须以某种方式知道表 2 中的数据链接到表 1 并共享价格。由于 abbrv 中的 Null 将排在第一位,因此无需创建 SortAbbrv 列。
关于sql - 使用不同数据集的 UNION ORDER BY (T-SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1004293/