我有2张桌子
表1
per_id | per_name
1 | joe
2 | mike
x | xxxx
和第二张桌子
per_id | job_q
1 | 500
1 | 250
2 | 125
2 | 10
3 | 54
...
i sql第三张表 我将所有job_q和按per_name分组并按job_q asc排序的
表3
per_name | job_q
joe | 750
mike | 135
...
如何在保持job_q顺序的同时将结果限制为特定的per_name?
答案 0 :(得分:1)
编辑-我假设OP在谈论KDB数据库中的qsql(因为使用了q
标签/标记)
像这样吗?
q)`job_q xdesc select sum job_q by per_name from (t2 lj 1!t1) where per_name in `joe`mike
per_name| job_q
--------| -----
joe | 750
mike | 135
假设您的表在内存中。
或者如果您想按ID进行过滤:
q)`job_q xdesc select sum job_q by per_name from (t2 lj 1!t1) where per_id=2
per_name| job_q
--------| -----
mike | 135
答案 1 :(得分:0)
您可以通过CTE做到这一点:
with cte as (
select t1.per_name, sum(t2.job_q) job_q
from table1 t1 inner join table2 t2
on t2.per_id = t1.per_id
group by t1.per_name
)
select * from cte
order by job_q desc
limit (
select count(*) from cte where job_q >= (
select job_q from cte where per_name = 'mike'
)
);
请参见demo