我有一个查询UNION
有两个相似的数据集,但是它们都有一些列不存在于另一个中(即,列在结果UNION
中有NULL值。 )
问题是,我需要ORDER
使用那些仅存在于一个或另一个集合中的列生成的数据,以便以软件方面的友好格式获取数据。
例如:表1 包含字段ID, Cat, Price
。 表2 包含字段ID, Name, Abbrv
。 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中完成。
答案 0 :(得分:28)
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列。
答案 1 :(得分:5)
您应该使用UNION ALL而不是UNION来节省重复检查的成本。
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
答案 2 :(得分:1)
一个快速的解决方案是将2个插入到临时表或表变量中,作为插入临时表的一部分,您可以设置一个标志列以帮助排序,然后按该标志列排序。
答案 3 :(得分:1)
在我的脑海中,我会说最糟糕的情况是你创建一个临时表,所有字段都从T1和amp; INSERT INTO临时表中执行。 T2然后从临时表中选择SELECT,顺序为。
即。创建一个临时表(例如#temp),其中包含字段Id,Cat,Price,Name,Abbrv,然后:
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
注意:我对插入的null语法不是100%肯定,但我认为它会起作用。
编辑:通过Price&添加订购id之后的abbrv ...如果Id没有链接T1&那么T2会是什么呢?