[英]Get Aggregate Count of Column After Group by in Mysql
I'm not a strong database person but i have an intermediate knowledge of it. 我不是一个强大的数据库人,但我对它有中级知识。 Here is my challenge which I'm facing, I have a table like - 这是我面临的挑战,我有一张像 -
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
I would like a mysql query that would select all rows that the pin=$pin and month=$month
and return all columns with an aggregate count of the value
我想要一个mysql查询,它将选择pin=$pin and month=$month
所有行,并返回所有具有该value
的聚合计数的列
For the sample dataset above , id like to get something like 对于上面的示例数据集,id喜欢得到类似的东西
pin type month year timestamp value
---- ----- --- --- --- -------- -----
123 clicks 12 2014 unixtime 10
Any help would be appreciated. 任何帮助,将不胜感激。
You need to use GROUP BY, SUM() and COUNT() 你需要使用GROUP BY,SUM()和COUNT()
SELECT COUNT(month) as month, SUM(value) AS value
FROM TABLE_NAME
WHERE pin = '$pin'
AND month='$month' // Added $month in condition
GROUP BY pin, month, year // Added some conditions
Explanation: 说明:
You need 你需要
1) all rows of pin
specified so, used WHERE
1)指定所有pin
行,使用WHERE
2) COUNT of month for the specified pin
so used, COUNT()
2)如此使用的指定pin
COUNT月, COUNT()
3) SUM of value for the specified pin
so used, SUM()
3)如此使用的指定pin
的值的SUM()
, SUM()
This could be done as 这可以做到
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
If you do not want the grouping per month then remove it from group by clause and use only year. 如果您不希望每月进行分组,则将其从group by子句中删除,并仅使用年份。
Note that the above query is mysql specific. 请注意,上面的查询是特定于mysql的。 In standard when you select some columns using aggregate function they must appear in he group by
clause. 在标准中,当您使用聚合函数选择某些列时,它们必须出现在group by
子句中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.