gpt4 book ai didi

MySQL查询相同数量的状态返回一组记录

转载 作者:行者123 更新时间:2023-11-29 16:13:24 25 4
gpt4 key购买 nike

如果我有电话列和州列。我可以查询特定的 LIMIT(假设为 500),但我希望状态列中可用的每个状态在 500 计数查询中具有相同的数量。

例如: table =铁人

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;

最佳答案

使用 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

关于MySQL查询相同数量的状态返回一组记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55052938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com