How do I create a SQL query that groups in certain percent range

前端 未结 2 1169
粉色の甜心
粉色の甜心 2021-01-27 11:12

I would like to create a SQL query that groups the increase price of items in certain percentage range. For example

2 items increased between 0 to 10 %

4 items i

相关标签:
2条回答
  • 2021-01-27 11:50
    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
    

    Note: MagicChangeTable may in fact be a subquery to calculate the percent change.

    0 讨论(0)
  • 2021-01-27 11:52

    If You want all ranges by 10: Use:

    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
    

    for such structure:

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

    edit: >=from and < to

    0 讨论(0)
提交回复
热议问题