【问题标题】:SQL query - limit resulting query rows based on non sorted valueSQL 查询 - 根据非排序值限制生成的查询行
【发布时间】:2019-08-02 04:59:36
【问题描述】:

我有两张桌子

表 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
...

我需要第三张表,在其中汇总所有 job_q 并按 per_name 分组并按 job_q asc 排序

表 3

per_name | job_q
---------+---------    
joe      | 750
mike     | 135
...

如何在保持 job_q 排序的同时将结果限制为特定的 per_name?

【问题讨论】:

    标签: sqlite


    【解决方案1】:

    编辑 - 我假设 OP 正在谈论 qsql,它是 KDB 数据库的一部分(因为使用了 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
    

    【讨论】:

      【解决方案2】:

      你可以通过 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

      【讨论】:

      • 我得到查询成功执行但没有结果...可能是因为表 1 和 2 不共享相同的名称?(表 1 上的 per_id 是 pr_id)在 db 浏览器上编码
      • 我不知道你的实际数据。当然,您可以将“mike”更改为您数据中的有效名称。
      • 您必须更改列和/或表的名称
      • 只执行select * from cte。你有任何数据吗?
      • 但我仍然成功执行查询
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 2021-06-13
      相关资源
      最近更新 更多