MySQL获取表的每个N元素的总和

时间:2017-02-10 16:23:18

标签: mysql sql

我有一张这样的表

ID - price - date
1  - 10    - 2017-01-01
2  - 50    - 2017-01-02
3  - 20    - 2017-01-01
4  - 10    - 2017-01-01
5  - 5     - 2017-01-01
6  - 10    - 2017-01-02
7  - 20    - 2017-01-02
8  - 20    - 2017-01-02

我希望得到不同日期的每2个元素的价格总和......

在这种情况下,我的结果必须是

2017-01-01 -> 30
2017-01-02 -> 60

2 个答案:

答案 0 :(得分:2)

一种方法是使用相关子查询:

select
    date,
    (   select sum(price)
        from (
            select price
            from your_table t2
            where t1.date = t2.date
            order by id
            limit 2
        )
    ) total 
from your_table t1
group by date;

答案 1 :(得分:2)

SELECT x.date
     , SUM(y.price) 
  FROM my_table x 
  JOIN my_table y 
    ON y.date = x.date 
   AND y.id <= x.id 
 GROUP 
    BY x.id -- a functional dependency
HAVING COUNT(*) = 2;

(实际上,我觉得这很奇怪,但似乎有效)