col1 col2
| 2015-02-01 12
| 2015-02-01 10
| 2015-02-01 5
| 2015-02-02 8
| 2015-02-03 25
| 2015-02-03 10
| 2015-02-04 20
以上是我所拥有的表格样本。我希望在给定指定范围的情况下获得col2的总和。 如果我在01-02-2015到03-02-2015之间获取总和(col2)记录,那么我的输出应该是,
| 2015-02-01 27
| 2015-02-02 8
| 2015-02-03 35
是否有可能在mysql中实现这一点?
答案 0 :(得分:1)
如果col1是DATE列,则可以使用此查询:
SELECT col1, SUM(col2) AS sum_of_col2
FROM tablename
WHERE col1 BETWEEN '2015-02-01' AND '2015-02-03'
GROUP BY col1
如果col1是DATETIME列,并且包含DATE但也包含TIME信息,则应使用此:
SELECT
DATE(col1) AS date_of_col1,
SUM(col2) AS sum_of_col2
FROM
tablename
WHERE
col1>='2015-02-01' AND
col1<'2015-02-03' + INTERVAL 1 DAY
GROUP BY
DATE(col1)
答案 1 :(得分:0)
SELECT SUM(col2)
FROM table_name
WHERE col1 BETWEEN '2015-02-01' AND '2015-02-03'
GROUP BY col1
答案 2 :(得分:0)
您可以在clause之间使用分组来获得答案:
SELECT col1, sum(col2) as col2 FROM test where col1 BETWEEN '01-02-15' AND '03-02-15' GROUP BY col1