时间:2015-06-18 15:50:50

标签: mysql sql group-by case amazon-redshift

我有一个结构类似于下面的数据集

fruit, value
apple, 234
apple, 2341
pear, 3233
grape, 323
pear, 3234
grap 1234

我试图通过执行如下所示的查询来查找范围最后10%的数字范围的计数。 (查询的最终目标是计算并查看计算的范围以10%的增量上升)我还有一个group by子句,所以我希望计数按果实分组并按这种方式汇总。贝娄是我试过的查询

select fruit, count(case when (value <= (((max(value) - min(value)) * .1) + min(value))) then 1 end)
from fruit_juice
group by substring(fruit, 5, 5);

1 个答案:

答案 0 :(得分:0)

from子句中聚合表以获得所需的限制。 Join这些结果会返回到您的查询并将这些值用于查询:

select substring(fj.fruit, 5, 5),
       sum(fj.value <= fmm.minv + (fmm.maxv - fmm.minv) * 0.1)
from fruit_juice fj join
     (select substring(fruit, 5, 5) as fruit5,
             max(value) as maxv, min(value) as minv
      from fruit_juice
      group by substring(fruit, 5, 5)
     ) fmm
     on fmm.fruit5 = substring(fj.fruit, 5, 5)
group by substring(fruit, 5, 5);

请注意,您的group by表达式应与select子句中的表达式匹配。

编辑:

我不确定substring()在您的问题中的来源,因此此版本将其删除:

select fj.fruit, sum(fj.value <= fmm.minv + (fmm.maxv - fmm.minv) * 0.1)
from fruit_juice fj join
     (select fruit,
             max(value) as maxv, min(value) as minv
      from fruit_juice
      group by fruit
     ) fmm
     on fmm.fruit = fj.fruit
group by fruit;