HAVING SUM 问题
HAVING SUM issue
我对 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 |
+----+------------+--------+
我想要return数字SUM
为6且date
> '2010-01-04'
的日期
我要return字段号相加等于6的日期(具体日期之后,本例为2010-01-04)。示例:我的查询应该 return 2010-01-07 因为 2 in 2010-01-05 1 in 2010-01-06 3 in 2010-01-07
我测试了这个查询但没有成功:
SELECT date, SUM(number) AS total FROM MyTable
GROUP BY date
HAVING SUM(number) = 6
看起来您几乎在您的原始问题中有正确的查询。我添加了一个 WHERE
子句来限制仅比 2010-01-04
:
最近的日期
SELECT date, SUM(number) AS total
FROM MyTable
WHERE date > '2010-01-04'
GROUP BY date
HAVING SUM(number) = 6
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
认为自联接可能是最简单的方法,在日期等于或大于自身的地方将 table 与自身联接。
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
我对 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 |
+----+------------+--------+
我想要return数字SUM
为6且date
> '2010-01-04'
我要return字段号相加等于6的日期(具体日期之后,本例为2010-01-04)。示例:我的查询应该 return 2010-01-07 因为 2 in 2010-01-05 1 in 2010-01-06 3 in 2010-01-07
我测试了这个查询但没有成功:
SELECT date, SUM(number) AS total FROM MyTable
GROUP BY date
HAVING SUM(number) = 6
看起来您几乎在您的原始问题中有正确的查询。我添加了一个 WHERE
子句来限制仅比 2010-01-04
:
SELECT date, SUM(number) AS total
FROM MyTable
WHERE date > '2010-01-04'
GROUP BY date
HAVING SUM(number) = 6
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
认为自联接可能是最简单的方法,在日期等于或大于自身的地方将 table 与自身联接。
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