sql – 使用union的不同顺序

前端之家收集整理的这篇文章主要介绍了sql – 使用union的不同顺序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想写一个像这样的查询
  1. select top 10 * from A
  2. order by price
  3. union
  4. select top 3 * from A
  5. order by price

或者……那样的

  1. select top 10 * from A
  2. where name like '%smt%'
  3. order by price
  4. union
  5. select top 3 * from A
  6. where name not like '%smt%'
  7. order by price

你能帮我么?

解决方法

这应该工作:
  1. SELECT *
  2. FROM (SELECT TOP 10 A.*,0 AS Ordinal
  3. FROM A
  4. ORDER BY [Price]) AS A1
  5.  
  6. UNION ALL
  7.  
  8. SELECT *
  9. FROM (SELECT TOP 3 A.*,1 AS Ordinal
  10. FROM A
  11. ORDER BY [Name]) AS A2
  12.  
  13. ORDER BY Ordinal

MSDN开始:

In a query that uses UNION,EXCEPT,or INTERSECT operators,ORDER BY
is allowed only at the end of the statement. This restriction applies
only to when you specify UNION,EXCEPT and INTERSECT in a top-level
query and not in a subquery.

已编辑:强制将ORDER BY应用于外部查询所需的顺序.我为两个查询添加了一个常量值列.

猜你在找的MsSQL相关文章