我有下表。
select * from `consumo`;
输出:
+----+------------+-----------------+---------------------+
| id | cedula | registroConsumo | fecha-hora |
+----+------------+-----------------+---------------------+
| 1 | 0931111111 | 20 | 2016-08-17 13:52:48 |
| 2 | 0931111111 | 25 | 2016-08-17 13:53:01 |
| 3 | 0311111111 | 27 | 2016-08-17 13:54:23 |
| 4 | 0311111111 | 10 | 2016-08-17 13:54:26 |
| 5 | 0311111111 | 12 | 2016-08-17 13:54:29 |
| 6 | 0311111111 | 14 | 2016-08-17 13:54:34 |
| 7 | 0311111111 | 19 | 2016-08-17 13:54:38 |
| 8 | 0311111111 | 190 | 2016-08-17 13:54:44 |
| 9 | 0311111111 | 195 | 2016-08-17 13:54:48 |
| 10 | 0912223333 | 19 | 2016-08-17 13:54:54 |
| 11 | 0111111111 | 20 | 2016-08-17 13:54:59 |
| 12 | 0111111111 | 23 | 2016-08-17 13:55:03 |
| 13 | 0111111111 | 27 | 2016-08-17 13:55:07 |
| 14 | 0111111111 | 35 | 2016-08-17 13:55:11 |
| 15 | 0111111111 | 10 | 2016-08-17 13:55:14 |
| 16 | 0111111111 | 35 | 2016-09-04 12:10:01 |
| 17 | 0111111111 | 330 | 2016-09-04 12:10:06 |
+----+------------+-----------------+---------------------+
我想按年份和月份进行分组,但只显示月份和年份的实际结果全部都在Mysql中。
我这样做了:
select SUM(`registroConsumo`) from `consumo`
GROUP BY YEAR(`fecha-hora`),MONTH(`fecha-hora`)
HAVING YEAR(`fecha-hora`) = SELECT EXTRACT (YEAR FROM (SELECT NOW()))
AND MONTH(`fecha-hora`) = SELECT EXTRACT (MONTH FROM (SELECT NOW())) ;
我收到此错误:
错误1064(42000):您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便在第1行
SELECT EXTRACT (YEAR FROM (SELECT NOW())) AND MONTH(`fecha-hora`) = SELECT EXTRA
附近使用正确的语法
答案 0 :(得分:0)
在having
子句中出现的子查询中有几个缺少的括号。
但您可以更实际地处理此问题,并使用order by
和limit
返回您获得的最新数据:
select YEAR(`fecha-hora`),
MONTH(`fecha-hora`)
SUM(`registroConsumo`)
from `consumo`
group by YEAR(`fecha-hora`),
MONTH(`fecha-hora`)
order by YEAR(`fecha-hora`) DESC,
MONTH(`fecha-hora`) DESC
limit 1
或者,如果它真的必须与当前年月相匹配:
select YEAR(`fecha-hora`),
MONTH(`fecha-hora`)
SUM(`registroConsumo`)
from `consumo`
where YEAR(`fecha-hora`) = YEAR(NOW())
and MONTH(`fecha-hora`) = MONTH(NOW())
group by YEAR(`fecha-hora`),
MONTH(`fecha-hora`)