私信  •  关注

sticky bit Strawberry

sticky bit Strawberry 最近创建的主题
sticky bit Strawberry 最近回复了
6 年前
回复了 sticky bit Strawberry 创建的主题 » 按总和对mysql查询进行分组(阈值)

例如。:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(date DATE NOT NULL PRIMARY KEY
,number INT NOT NULL
);

INSERT INTO my_table VALUES
('2018-12-01',500),
('2018-12-02',400),
('2018-12-03',300),
('2018-12-04',500),
('2018-12-05',400);

SELECT MIN(CASE WHEN total >=  500 THEN date END) milestone_500 
     , MIN(CASE WHEN total >= 1000 THEN date END) milestone_1000 
     , MIN(CASE WHEN total >= 2000 THEN date END) milestone_2000 
  FROM
     (
       SELECT x.*,SUM(y.number) total FROM my_table x JOIN my_table y ON y.date <= x.date GROUP BY x.date
     ) a;

+---------------+----------------+----------------+
| milestone_500 | milestone_1000 | milestone_2000 |
+---------------+----------------+----------------+
| 2018-12-01    | 2018-12-03     | 2018-12-05     |
+---------------+----------------+----------------+