查询SQL分组求和小于总数的记录

img

求解:
两个表关联查询,查找表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
不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^