如何创建以特定百分比范围分组的SQL查询

时间:2011-10-11 21:42:21

标签: mysql sql

我想创建一个SQL查询,将特定百分比范围内项目的增加价格分组。例如

2项增加0至10%

4项增加10%至20%

2项增加20%至30%

...

目标服务器:MySQL

2 个答案:

答案 0 :(得分:2)

SELECT SUM(CASE WHEN PercentChange >= 0 AND PercentChange <= 10 THEN 1 ELSE 0) END AS ZeroTen,
       SUM(CASE WHEN PercentChange > 10 AND PercentChange <= 20 THEN 1 ELSE 0) END AS TenTwenty,
       SUM(CASE WHEN PercentChange > 20 AND PercentChange <= 30 THEN 1 ELSE 0) END AS TwentyThirty
    FROM MagicChangeTable

注意:MagicChangeTable实际上可能是一个子查询来计算变化百分比。

答案 1 :(得分:0)

如果您希望所有范围均为10: 使用:

SELECT (d-10)*10 AS `from` , (d-9)*10 AS `to` , c AS `count` FROM 
   (SELECT DISTINCT(FLOOR((`p`.`new`*10)/(`p`.`old`))) AS d,
      count(1) AS c FROM prices as p GROUP BY 1) AS stats

对于这样的结构:

CREATE TABLE `prices` (
  `old` int(11) NOT NULL,
  `new` int(11) NOT NULL
);

编辑:&gt; =来自&lt;到