SQL 中自动化程度不均 buckets/bins

Uneven automated buckets/bins in SQL

广告 Table:
- 每天每个广告一行

date    |   ad_id  | account_id | spend  
2018-05-01   123     1101        100  
2018-05-02   123     1101        125  
2018-05-03   124     1101        150  
2018-05-04   124     1101        150    
2018-05-04   125     1105        150  
2018-05-04   126     1105        150  
2018-05-04   123     1101        150  
2018-01-01   123     1101        150              

我正在尝试创建一个直方图来显示广告商在过去 7 天内花费了多少。 我希望第一个桶为 10-999.99 美元,其他桶为 1000-1999.99 美元、2000-2999.99 美元等,但我想通过自动化实现这一点,而不是通过 case 函数手动提及桶。

我当前的代码甚至在创建自动存储桶方面也做得很好:

select CONCAT(1000*FLOOR(last_7_days_spend/1000), "-", 1000*FLOOR(last_7_days_spend/1000)+999.99) "spend($)" , count(*) "frequency"
from
(select account_id, sum(spend) "last_7_days_spend"
from fb_ads
where date between date_sub(curdate(), interval 7 day) and date_sub(curdate(), interval 1 day)
group by account_id) as abc
group by 1
order by 1;

它 returns 这个:

spend       |   frequency
0-999.99        2  
2000-2999.99    1

但是想要编写一些类似的查询,它应该过滤掉记录并从 10-999.99 美元开始,而不是 0.00-999.99 美元。 期望的输出:

spend       |   frequency  
10-999.99       2  
2000-2999.99    1

您需要使用 CASE 表达式来定义第一个存储桶,但您可以自动执行该表达式中的其他存储桶。请注意,如果您不想要低于 10 美元的支出,则需要过滤掉这些值:

SELECT
    CASE WHEN last_7_days_spend < 1000 THEN '10-999.99'
         ELSE CONCAT(1000*FLOOR(last_7_days_spend/1000), "-", 1000*FLOOR(last_7_days_spend/1000)+999.99)
    END AS `spend($)`,
    COUNT(*) AS `frequency`
FROM (
    SELECT account_id, SUM(spend) AS `last_7_days_spend`
    FROM fb_ads
    WHERE date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND DATE_SUB(CURDATE(), INTERVAL 1 DAY)
    GROUP BY account_id
) as abc
WHERE last_7_days_spend >= 10
GROUP BY 1
ORDER BY 1

demo on db-fiddle