通过联合使用不同的顺序

时间:2012-11-19 13:29:21

标签: sql sql-server tsql

我想写一个像

这样的查询
    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 

你能帮帮我吗?

5 个答案:

答案 0 :(得分:15)

这应该有效:

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应用于外部查询所需的顺序。我为两个查询添加了一个常量值列。

答案 1 :(得分: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

答案 2 :(得分: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集。

[现在不再适用于您的问题,因为它已被编辑!]

答案 3 :(得分: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

答案 4 :(得分:-2)

cmd.CommandText =“ SELECT 0 AS Employee_ID,'No Employees'作为Employee_FullName,'id1'Orderkey         全联盟         选择Employee_ID,Employee_FullName,'id2'Orderkey         来自tblEmployee         ORDER BY Orderkey,Employee_FullName”

ds = dbconn.SelectQuery(cmd)

ds.Tables(0).Columns.Remove(ds.Tables(0).Columns(“ Orderkey”))