SQL - 将UNION和SORT BY结合起来用于多个语句

时间:2017-09-11 17:38:32

标签: sql select

我有一个100.000用户的列表,我需要查询电子邮件域并获得每个10000分。需要先得分4分。如果没有足够的去得分3等等。意味着优先级查询我收到的解决方案正好用于一个声明

SELECT TOP 10000 * 
FROM [table] 
WHERE Email like '%@test.com' and score in ( 1, 2, 3, 4) 
order by score desc

一旦我尝试将其用于多个语句,我就会收到无效的语法错误:

SELECT TOP 10000 * FROM 
[table] 
WHERE Email like '%@test.com'and score in ( 1, 2) 
order by score desc 
UNION 
SELECT TOP 1000 * FROM
[table] WHERE Email like '%@test2.com' and score in ( 1, 2, 3, 4)
order by score desc

我需要能够添加尽可能多的EMAILS。非常感谢帮助:)

2 个答案:

答案 0 :(得分:0)

从第一个查询中删除订单。

答案 1 :(得分:0)

只需在底部离开订单,然后删除其他人的订单

  SELECT TOP 10000 * FROM [table] 
  WHERE Email like '%@test.com' and score in ( 1, 2) 
  UNION 
  SELECT TOP 1000 * FROM [table] 
  WHERE Email like '%@test2.com' and score in ( 1, 2, 3, 4) 
  order by score desc 

否则,如果您需要在每个中选择已构建的值,请选择uing()

  select TOP 11000 * from 
  (SELECT TOP 10000 * FROM [table] 
  WHERE Email like '%@test.com' and score in ( 1, 2) 
  order by score desc ) t1
  UNION 
  select * from 
  ( SELECT TOP 1000 * FROM [table] 
  WHERE Email like '%@test2.com' and score in ( 1, 2, 3, 4) 
  order by score desc ) t2
  ORDER BY score DESC