开发者

how to select lines in Mysql while a condition lasts

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 
for开发者_开发问答each 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!!!!


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜