MySQL在返回的记录数量中查询相同数量的状态

时间:2019-03-07 21:17:50

标签: mysql sql

如果我有一个电话专栏和一个状态专栏。我可以查询特定的LIMIT(例如500),但我希望state列中的每个州在500计数查询中具有相等的数量。

ex:表格= ironman

appid
phone(PK)
firstname
lastname
address
city
state
zip
called_count

查询:

SELECT 
FROM ironman
(A scripts that gives me (x amount) of phone numbers from each state)
WHERE called_count <= 4
LIMIT 500 OFFSET 0;

1 个答案:

答案 0 :(得分:0)

使用ROW_NUMBER()在状态组中为行分配位置。然后按该位置对行进行排序。然后,当您应用LIMIT时,每个州的行数(+ -1)-相同(假设每个州的电话号码都足够)。

with numbered as (
  select i.*
       , row_number() over (partition by state order by phone) pos
  from ironman i
  -- put your WHERE clause here
), limited as (
  select *
  from numbered
  order by pos asc, state asc
  limit 6 -- set your limit here
)
select *
from limited
order by state, phone

db-fiddle

如果您希望随机选择电话号码-更改位置的订单

row_number() over (partition by state order by rand()) pos