求解:
两个表关联查询,查找表2中类型1数量分组降序排列后,前n项求和小于表1总数的记录。谢谢~
SELECT SUM(`类型1数`) AS `总数`, `类型`
FROM `表2`
GROUP BY `类型`
HAVING SUM(`类型1数`) IN (
SELECT `类型1数` FROM (
SELECT `类型1数`, ROW_NUMBER() OVER (ORDER BY `类型1数` DESC) AS `rank`
FROM `表2`
) AS `t`
WHERE `rank` <= n
)
AND SUM(`类型1数`) < (SELECT `总数` FROM `表1` WHERE `类型` = '某种类型')
with t1 as (
select 'a1' as tp,100 as num
union all select 'a2',80
union all select 'a3',110
),t2 as (
select 'a01' tp1,60 num,'a1' tp
union all select 'a02',30,'a1'
union all select 'a03',70,'a2'
union all select 'a04',50,'a2'
union all select 'a05',60,'a3'
union all select 'a06',40,'a3'
union all select 'a07',30,'a3'
union all select 'a08',20,'a3'
),t3 as ( -- 使用row_number 排序并分配序号
select *,row_number() over(partition by tp order by num desc) nid from t2
),t4 as ( -- 使用cte递归查询,每个数据加上后剩余数量,根据剩余数量判断是否继续追加
select a.*,b.num total,b.num-a.num less
from t3 a
left join t1 b on a.tp=b.tp and a.num<=b.num
where nid = 1
union all
select a.*,b.total,b.less-a.num
from t3 a,t4 b
where a.tp=b.tp and a.nid=b.nid+1
and a.num<=b.less
)
select * from t4 -- 查询最终结果
order by tp,nid
不知道你这个问题是否已经解决, 如果还没有解决的话:当行数是不被n整除,则ntile()函数导致两种尺寸的组。较大的群体总是提前由order by函数指定的顺序中的第一组。当所有行被n整除,则每组的行数相同。