我想写一个查询
select top 10 * from A order by price union select top 3 * from A order by price
或诸如此类
select top 10 * from A where name like '%smt%' order by price union select top 3 * from A where name not like '%smt%' order by price
你能帮我么?
这应该工作:
SELECT * FROM (SELECT TOP 10 A.*, 0 AS Ordinal FROM A ORDER BY [Price]) AS A1 UNION ALL SELECT * FROM (SELECT TOP 3 A.*, 1 AS Ordinal FROM A ORDER BY [Name]) AS A2 ORDER BY Ordinal
从 MSDN :
在使用UNION,EXCEPT或INTERSECT运算符的查询中,仅在语句末尾才允许使用ORDER BY。仅当您在顶级查询中 而不是子查询中 指定UNION,EXCEPT和INTERSECT时,此限制才适用。
编辑 :强制您需要将顺序应用于ORDER BY外部查询的顺序。我已经向两个查询添加了一个常量值列。
ORDER BY