简体   繁体   中英

SQL - combine UNION and SORT BY for several statements

I have a list of 100.000 User which I need to query for email domain and score for 10000 each. It is needed to take all with score 4 first. If there are not enough go to score 3 and so on.Meaning a priorization query The solution I received is working fine for one statement

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

as soon as I am trying to use that for multiple statements I receive invalid syntax errors:

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

I would need to be able to add as many EMAILS as I want. Help is higly appreciated :)

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

just leave the order by at the bottom and remove the order by for the others

  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 

otherwise if you need the ordered values in each select the build separated select 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM