Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取Mysql中Group by之后的列的聚合计数_Php_Mysql - Fatal编程技术网

Php 获取Mysql中Group by之后的列的聚合计数

Php 获取Mysql中Group by之后的列的聚合计数,php,mysql,Php,Mysql,我不是一个很擅长数据库的人,但我对它有中级知识。这是我面临的挑战,我有一张像- pin type day month year timestamp value ---- ----- --- --- --- -------- ----- 123 clicks 02 12 2014 unixtime 3 123 clicks 03 12 2014 unixtime 7 111 clicks 02 12 2014 unixtime 10 我想要一个

我不是一个很擅长数据库的人,但我对它有中级知识。这是我面临的挑战,我有一张像-

pin  type   day month year timestamp value
---- -----  --- ---   ---  --------  -----
123  clicks 02  12    2014 unixtime  3
123  clicks 03  12    2014 unixtime  7
111  clicks 02  12    2014 unixtime  10
我想要一个mysql查询,该查询将选择
pin=$pin和month=$month
的所有行,并返回聚合计数为
值的所有列

对于上面的示例数据集,我想得到如下内容

pin  type   month year  timestamp value
---- -----  ---   ---   ---       --------  -----
123  clicks 12    2014  unixtime  10

任何帮助都将不胜感激。

您需要使用GROUP BY、SUM()和COUNT()

说明:

你需要

1) 指定的
pin
的所有行,使用
WHERE

2) 指定的
pin使用的月份计数,
COUNT()

3) 指定的
引脚的值之和,因此使用
SUM()

这可以按如下方式完成

select
pin,
type,
day,
month,
year,
timestamp,
sum(value) as value 
from table_name
where pin='$pin' and month='$month'
group by pin,month,year
如果不希望每月分组,请将其从GROUPBY子句中删除,并仅使用年


注意,上面的查询是特定于mysql的。在标准中,当您使用聚合函数选择某些列时,它们必须出现在
group by
子句中。

对不起,我是否也要在where子句中添加
月份=$month
?谢谢你的回答只是为了记录在案,有一个打字错误(额外“和”in“和month=“$month”)@KonstantinosFilios,我真的很感谢你。输入错误更正。仅供参考,将变量直接放入这样的查询将打开SQL注入。你应该使用绑定。以防其他人看到这个答案寻求帮助
select
pin,
type,
day,
month,
year,
timestamp,
sum(value) as value 
from table_name
where pin='$pin' and month='$month'
group by pin,month,year