如何在条件持续时在Mysql中选择行
我有这样的事情:
Name.....Value
A...........10
B............9
C............8
意思是,这些值按降序排列。我需要创建一个新表,其中包含占总值 60% 的值。所以,这可能是一个伪代码:
set Total = sum(value)
set counter = 0
foreach line from table OriginalTable do:
counter = counter + value
if counter > 0.6*Total then break
else insert line into FinalTable
end
如您所见,我正在解析此处的 sql 行。我知道这可以使用处理程序来完成,但我无法让它工作。因此,任何使用处理程序或其他创意的解决方案都会很棒。 它还应该具有合理的时间复杂度 - 解决方案如何选择总和不超过总数 60% 的值 可以工作,但速度慢得要命:(
谢谢!!!!
I have something like this:
Name.....Value
A...........10
B............9
C............8
Meaning, the values are in descending order. I need to create a new table that will contain the values that make up 60% of the total values. So, this could be a pseudocode:
set Total = sum(value)
set counter = 0
foreach line from table OriginalTable do:
counter = counter + value
if counter > 0.6*Total then break
else insert line into FinalTable
end
As you can see, I'm parsing the sql lines here. I know this can be done using handlers, but I can't get it to work. So, any solution using handlers or something else creative will be great.
It should also be in a reasonable time complexity - the solution how to select values that sum up to 60% of the total
works, but it's slow as hell :(
Thanks!!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要使用
lead()
或lag()
窗口函数,可能带有 递归查询将行合并在一起。请参阅此相关问题:合并如果剧集直接连续或重叠,则为 DATE 行
如果您使用的是 MySQL,则可以使用类似的方法来解决缺少窗口函数的问题这个:
Mysql查询问题
You'll likely need to use the
lead()
orlag()
window function, possibly with a recursive query to merge the rows together. See this related question:merge DATE-rows if episodes are in direct succession or overlapping
And in case you're using MySQL, you can work around the lack of window functions by using something like this:
Mysql query problem
我不知道SQL Server(我假设你正在使用)支持哪些分析功能;对于 Oracle,您可以使用类似以下内容:
说明:
- sum(value) over ... 计算总和的运行总计
- lag() 为您提供前一行的值
- 然后您可以将它们组合起来找到第一行,其中percent_current > 0.6且percent_previous < 0.6
I don't know which analytical functions SQL Server (which I assume you are using) supports; for Oracle, you could use something like:
Explanation:
- sum(value) over ... computes a running total for the sum
- lag() gives you the value for the previous row
- you can then combine these to find the first row where percent_current > 0.6 and percent_previous < 0.6