【问题标题】:Limit by a cumulative column amount由累积列数量限制
【发布时间】:2018-10-08 08:52:29
【问题描述】:

假设我有一个包含 3 列的表格: id, row_type, row_score

我想选择第一行(或最后一行),但根据获取的 id 的累积分数限制选择

示例table

id | row_type | row_score
 1          a                  1
 2          a                  1
 3          b                  2
 4          c                  3
 5          a                  1
 6          b                  2
 7          a                  1
...

第 1 行的结果,累计分数限制为 4:

id | row_type | row_score
 1          a                  1
 2          a                  1
 3          b                  2

【问题讨论】:

  • 如果有 1、1 和 3 会怎样?它是停在两行 (1+1 = 2) 还是 3 (1+1+3 = 5)?
  • 好问题,我宁愿少写多行

标签: mysql sql limit


【解决方案1】:

这个查询应该做你想做的事。它使用一个变量来保持累积分数,然后在 HAVING 子句中使用它来限制返回的行:

SELECT t1.*, @cum_score := @cum_score + row_score AS cum_score
FROM table1 t1
JOIN (SELECT @cum_score := 0) c
HAVING cum_score <= 4
ORDER BY cum_score

输出:

id  row_type    row_score   cum_score
1   a           1           1
2   a           1           2
3   b           2           4

SQLFiddle Demo

【讨论】:

  • 我想你的意思是CROSS JOIN
  • @MadhurBhaiya 没有ON 条件JOINCROSS JOIN
  • @尼克。 . .没有ON 条件,没有ONJOIN 是一个语法错误——MySQL 碰巧忽略了。
  • @GordonLinoff MySQL 特别允许JOIN 在其语法中没有连接条件:join_table: table_reference [INNER | CROSS] JOIN table_factor [join_condition] 所以我不认为你真的可以说它忽略了语法错误。 dev.mysql.com/doc/refman/8.0/en/join.html
【解决方案2】:

这应该会给你想要的结果:

select t1.id, t1.row_type,t1.row_score, SUM(t2.row_score) as sum
from table t1
inner join table t2 
on t1.id >= t2.id
group by t1.id, t1.row_type,t1.row_score
having SUM(t2.row_score)<=4
order by t1.id

谢谢,

罗汉·霍达卡

【讨论】:

  • HAVING 条件“
  • 我在 BigQuery 上尝试了该查询,它对我有用。你能告诉我你得到了什么错误吗?
  • 查询已运行,​​但结果集为空。我现在在构建的 SQLfiddle @Nick 上对其进行了测试,它可以工作
猜你喜欢
  • 1970-01-01
  • 2022-10-21
  • 1970-01-01
  • 2015-06-14
  • 2018-04-11
  • 2023-03-22
  • 2015-05-05
  • 2020-09-14
  • 2014-12-09
相关资源
最近更新 更多