按连续时间分组

时间:2018-03-15 06:15:29

标签: mysql sql

嗨,我的栏目如下

+--------+--------+
| day    |  amount| 
+--------+---------
| 2      |   2    |
| 1      |   3    | 
| 1      |   4    | 
| 2      |   2    |
| 3      |   3    | 
| 4      |   3    |
| 5      |   6    |
| 6      |   6    |
+--------+--------+

现在我希望像这样的第1天 - 第3天作为第一行,将第2天 - 第4天作为第2行,依此类推。

+--------+--------+
| day    |  amount| 
+--------+---------
| 1-3    |   14   |
| 2-4    |   10   | 
| 3-5    |   12   |
| 4-6    |   15   |
+--------+--------+

你能提供任何帮助吗,谢谢!

3 个答案:

答案 0 :(得分:3)

我只想使用相关的子查询:

select day, day + 2 as end_day,
       (select sum(amount)
        from t t2
        where t2.day in (t.day, t.day + 1, t.day + 2)
       ) as amount
from (select distinct day from t) t;

这将返回所有日期的行,不限于最后一行4.如果您确实需要该限制,则可以使用:

select day, day + 2 as end_day,
       (select sum(amount)
        from t t2
        where t2.day in (t.day, t.day + 1, t.day + 2)
       ) as amount
from (select distinct day
      from t
      order by day
      offset 1 limit 99999999
     ) t
order by day;

答案 1 :(得分:1)

方式1:

只需使用UNION ALL

SELECT '1 - 3' [Day], SUM(Amount)Amount FROM Your_Table WHERE Day BETWEEN 1 AND 3
UNION ALL
SELECT '2 - 4', SUM(Amount) FROM Your_Table WHERE Day BETWEEN 2 AND 4
UNION ALL
SELECT '3 - 5', SUM(Amount) FROM Your_Table WHERE Day BETWEEN 3 AND 5
UNION ALL
SELECT '4 - 6', SUM(Amount) FROM Your_Table WHERE Day BETWEEN 4 AND 6

方式2:

您必须创建一个日期范围为JOIN表的表格。

CREATE TABLE Tab1 (Day INT, Amount INT)
INSERT INTO Tab1 VALUES( 2 ,2 )   
 ,(1, 3)    
 ,(1, 4)    
 ,(2, 2)   
 ,(3, 3)    
 ,(4, 3)   
 ,(5, 6)   
 ,(6, 6)

CREATE TABLE Tab2 (DateRange VARCHAR(10), StartDate INT, EndDate INT)
INSERT INTO Tab2 VALUES ('1 - 3',1,3)
    ,('2 - 4',2,4)
    ,('3 - 5',3,5)
    ,('4 - 6',4,6)

SELECT T2.DateRange,SUM(T1.Amount) Amount
FROM Tab1 T1
JOIN Tab2 T2 ON T1.Day BETWEEN T2.StartDate AND T2.EndDate
GROUP BY T2.DateRange

<强>输出:

Day     Amount
1 - 3   14
2 - 4   10
3 - 5   12
4 - 6   15

答案 2 :(得分:1)

您可以使用整数除法来计算“天”数据块&#39;每个桶分组:

SELECT (day - 1) DIV 3 AS bucket, SUM(amount) AS total
FROM mytable
GROUP BY (day - 1) DIV 3;

<强>输出:

bucket  total
-------------
0       14
1       15

Demo here

要获取可以使用的存储桶字符串:

SELECT concat(3 * ((day - 1) DIV 3 + 1) - 2, ' - ',
              3 * ((day - 1) DIV 3 + 1)) AS bucket, 
       SUM(amount) AS total
FROM mytable
GROUP BY (day - 1) DIV 3
order by day;

<强>输出:

bucket  total
--------------
1 - 3   14
4 - 6   15

注意:该查询仅适用于连续的非重叠间隔。