有SUM问题

时间:2015-09-03 08:27:38

标签: mysql sum conditional-statements having

我对HAVING SUM的声明有疑问。

My table:

id int(11) AUTO_INCREMENT
date date
number int(3)

+----+------------+--------+
| id | date       | number |
+----+------------+--------+    
| 1  | 2010-01-02 |   0    |
| 2  | 2010-01-03 |   3    |
| 3  | 2010-01-04 |   0    |
| 4  | 2010-01-05 |   2    |
| 5  | 2010-01-06 |   1    |
| 6  | 2010-01-07 |   3    |
+----+------------+--------+

我想要返回SUM的数字为6且date>的日期。 '2010-01-04'

我希望返回添加字段编号等于6的日期(在特定日期之后,在此示例中为2010-01-04)。示例:我的查询应返回2010-01-07,因为2010-01-05中的2 2010-01-06中的2 2010-01-07中的2

我测试了此查询但没有成功:

SELECT date, SUM(number) AS total FROM MyTable 
GROUP BY date
HAVING SUM(number) = 6

3 个答案:

答案 0 :(得分:2)

看起来你几乎在原始问题中有正确的查询。我添加了一个WHERE子句,仅限于比2010-01-04更新的日期:

SELECT date, SUM(number) AS total
FROM MyTable
WHERE date > '2010-01-04'
GROUP BY date
HAVING SUM(number) = 6

答案 1 :(得分:0)

select date 
    from 
      (select date, @n:=@n+total total 
          from 
            (select date, sum(number) total 
                from MyTable 
              where date > '2010-01-04' 
              group by date 
              order by date 
            ) t 
           cross join 
            (select @n:=0) n 
      ) tt 
   where total = 6

答案 2 :(得分:0)

认为自我加入可能是最简单的方法,在日期等于或大于自身的情况下加入自己的表格。

SELECT t1.date
FROM sometable t1
INNER JOIN sometable t2
ON t1.date <= t2.date
WHERE date > '2010-01-04'
GROUP BY t1.date
HAVING SUM(number) = 6