选择总和值为总和的80%的行

时间:2017-07-17 21:02:53

标签: sql tsql percentage

以下是业务问题的一个示例。

我有10个销售额导致负利润。 我们想查看这些记录,我们通常在评论中使用20/80规则。 这是20%的销售额可能代表80%的负利润。

以下记录......

+----+-------+
| ID | Value |
+----+-------+
|  1 |    30 |
|  2 |    30 |
|  3 |    20 |
|  4 |    10 |
|  5 |     5 |
|  6 |     5 |
|  7 |     2 |
|  8 |     2 |
|  9 |     1 |
| 10 |     1 |
+----+-------+

我想回来......

+----+-------+
| ID | Value |
+----+-------+
|  1 |    30 |
|  2 |    30 |
|  3 |    20 |
|  4 |    10 |
+----+-------+

总值为106,80%则为84.8。 我需要所有记录,排序下降,总和值让我至少达到84.8

我们使用Microsoft APS PDW SQL,但如果需要,可以在SMP上进行处理。

3 个答案:

答案 0 :(得分:4)

假设支持窗口功能,您可以使用

with cte as (select id,value
             ,sum(value) over(order by value desc,id) as running_sum 
             ,sum(value) over() as total
             from tbl
            ) 
select id,value from cte where running_sum < total*0.8
union all
select top 1 id,value from cte where running_sum >= total*0.8 order by value desc

答案 1 :(得分:0)

一种方法是使用运行总计:

select
  id,
  value
from
(
  select
    id,
    value,
    sum(value) over () as total,
    sum(value) over (order by value desc) as till_here,
    sum(value) over (order by value desc rows between unbounded preceding and 1 preceding)
      as till_prev
  from mytable
) summed_up
where till_here * 1.0 / total <= 0.8
   or (till_here * 1.0 / total >= 0.8 and coalesce(till_prev, 0) * 1.0 / total < 0.8)
order by value desc;

答案 2 :(得分:0)