每个组的KDB前排

时间:2019-02-21 11:24:59

标签: kdb

我想查询部门表SQL Like的前5名薪水收入者

    SELECT * FROM (
                    SELECT empno, salary, RANK () OVER (PARTITION BY deptno ORDER BY salary DESC) emprank FROM emp ) 
    WHERE emprank <= 3;

我正尝试做类似的事情。

select from emp where ({x in 3#x};i) fby deptno

,但无法产生预期的结果。请给我一个线索。

3 个答案:

答案 0 :(得分:2)

t在哪里

t:([]deptno:where 10 20 8;salary:40000+38?30000;emp:neg[38]?`3)

您可以通过以下信息返回部门中收入最高的前3名

q)select from t where 3>(iasc idesc@;salary)fby deptno
deptno salary emp
-----------------
0      69894  mfm
0      55539  bbb
0      62673  jnd
1      66668  afk
1      67474  kcj
1      69979  kon
2      60561  oco
2      57664  khd
2      58743  dga

请注意,我仅将表t用作示例表。让我知道您使用的表与我在这里使用的表是否有显着差异。

答案 1 :(得分:1)

其他执行速度更快,占用内存更少的替代方法:

q) select from t where ({til[count x] in 3#idesc x};salary) fby deptno

如果您希望所有前三名员工都属于该薪水类别,则可以使用以下解决方案。

q) select from t where ({x in x 3#idesc x};salary) fby deptno

如果您的表不是由deptno排序的,则可以使用'xasc / xdesc'来排序结果:

q) `deptno xasc select from t where ({til[count x] in 3#idesc x};salary) fby deptno

答案 2 :(得分:0)

另一个选择是:

select 3 sublist salary idesc[salary] by deptno from emp

sublist而不是#来处理一个部门的工资少于3的情况。