14

我想写一个查询

    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 

你能帮我么?

4

5 回答 5

22

这应该有效:

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 时。

已编辑:强制您需要将 anORDER BY应用于外部查询的顺序。我在两个查询中都添加了一个常量值列。

于 2012-11-19T13:32:47.287 回答
4

这是一种真正的hacky方式。您可能希望这些在现实中作为单独的查询,但这应该会给您想要的结果......

select *
from (
  select top 10 *, 1 as 'ord', price as 'ordprice' from A
  union 
  select top 3 *, 2 as 'ord', 0 as 'ordprice' from A
) a
order by ord, ordprice, name
于 2012-11-19T13:32:55.083 回答
2

UNION 不喜欢 UNIONed 表达式中的 ORDER by 子句。试试这个:

SELECT * FROM
   (SELECT TOP 10 * FROM A ORDER BY Price) SetA
UNION
SELECT * FROM
   (SELECT TOP 3 * FROM a ORDER BY name) Setb
[ORDER BY something]

这欺骗了 UNION 运算符忽略 ORDER BY,它们仍然在 TOP 运算符上正确运行。如果您愿意,您可以应用最终的 ORDER BY 来订购 UNIONed 集。

[现在已编辑,不再完全适用于您的问题!]

于 2012-11-19T13:36:57.947 回答
0
select top 10 *,0 as RS from A
union
select top 3 *,1 as RS from A 
order by
    RS,
    CASE WHEN RS=0 THEN price END, --Don't affect RS 1
    name
于 2012-11-19T13:33:37.037 回答
-2

cmd.CommandText = "SELECT 0 AS Employee_ID, 'No Employees' as Employee_FullName, 'id1' Orderkey UNION ALL SELECT Employee_ID, Employee_FullName, 'id2' Orderkey FROM tblEmployee ORDER BY Orderkey, Employee_FullName"

ds = dbconn.SelectQuery(cmd)

ds.Tables(0).Columns.Remove(ds.Tables(0).Columns("Orderkey"))

于 2018-06-19T12:14:49.293 回答