how to select lines in Mysql while a condition lasts

血红的双手。 提交于 2019-12-10 16:22:23

问题


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!!!!


回答1:


You'll likely need to use the lead() or lag() 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




回答2:


I don't know which analytical functions SQL Server (which I assume you are using) supports; for Oracle, you could use something like:

select v.*,
  cumulative/overall percent_current,
  previous_cumulative/overall percent_previous from (
  select 
    id, 
    name, 
    value, 
    cumulative,
    lag(cumulative) over (order by id) as previous_cumulative,
    overall
  from (
    select 
      id, 
      name, 
      value, 
      sum(value) over (order by id) as cumulative,
      (select sum(value) from mytab) overall
    from mytab
    order by id) 
) v

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



来源:https://stackoverflow.com/questions/6186854/how-to-select-lines-in-mysql-while-a-condition-lasts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!