将不同项分组到存储桶中的SQL查询

时间:2011-07-12 19:13:01

标签: sql postgresql

我正在尝试编写一个查询,该查询返回其价格属于certrain存储区的项目数:

例如,如果我的表是:

item_name | price
i1        | 2
i2        | 12
i3        | 4
i4        | 16
i5        | 6

输出:

range   | number of item
0 - 10  |  3
10 - 20 |  2

到目前为止,我的方式是

SELECT count(*)
FROM my_table
Where price >=0
and price <10

然后

SELECT count(*)
FROM my_table
Where price >=10
and price <20

然后将每次粘贴我的结果复制到excel中。

是否有自动方法在SQL查询中执行此操作?

4 个答案:

答案 0 :(得分:39)

Kerrek描述的扩展选项,您可以根据案例/何时

进行分组
select
      case when price >= 0 and price <= 10    then '  0 - 10'
           when price > 10 and price <= 50   then ' 10+ - 50'
           when price > 50 and price <= 100  then ' 50+ - 100'
           else 'over 100'
      end PriceRange,
      count(*) as TotalWithinRange
   from
      YourTable
   group by 1

这里,“group by 1”表示select语句中的序数列...在这种情况下,case / when为TotalWithinRange。

答案 1 :(得分:16)

您可以尝试按10单位价格进行分组:

SELECT COUNT(*) AS tally,
       FLOOR(price/10) AS prange,
       CONCAT(10*FLOOR(price/10), "-", 10*FLOOR(price/10)+9) AS rstr
FROM my_table
GROUP BY prange;

答案 2 :(得分:0)

对DRapp代码进行一些修改......

select
case when price >= 0 and price < 10    then "  0 - 10"
           when price > 10 and price <= 50   then " 10+ - 50"
           when price > 50 and price <= 100  then " 50+ - 100"
           else "over 100"
end As PriceRange,
count(item_name) as ItemTotal
from YourTable
group by 
case when price >= 0 and price < 10    then "  0 - 10"
           when price > 10 and price <= 50   then " 10+ - 50"
           when price > 50 and price <= 100  then " 50+ - 100"
           else "over 100"
end;

答案 3 :(得分:0)

这是一个简单的mysql解决方案。首先,根据价格计算桶指数。

select *, floor(price/10) as bucket from mytable
+------+-------+--------+
| name | price | bucket |
+------+-------+--------+
| i1   |     2 |      0 |
| i2   |    12 |      1 |
| i3   |     4 |      0 |
| i4   |    16 |      1 |
| i5   |     6 |      0 |
+------+-------+--------+

接下来,按桶索引分组并计算价格总和并格式化 prange 列。

select concat(bucket * 10, '-', (bucket * 10 - 1) + 10) as prange, count(price)
from  (select *, floor(price/10) as bucket from mytable) t1 
group by bucket;
+--------+--------------+
| prange | count(price) |
+--------+--------------+
| 0-9    |            3 |
| 10-19  |            2 |
+--------+--------------+