我不是一个强大的数据库人,但我有一个中级的知识。这是我面临的挑战,我有一张桌子-
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 and month=$month中的所有行,并返回带有value集合计数的所有列。
对于上面的示例数据集,id希望得到类似于
pin type month year timestamp value
---- ----- --- --- --- -------- -----
123 clicks 12 2014 unixtime 10任何帮助都将不胜感激。
发布于 2014-12-23 10:53:30
您需要使用组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解释:
你需要
1)所有指定的pin行,使用WHERE
2)如此使用的指定pin的月计数,COUNT()
3)如此使用的指定pin的值之和,SUM()
发布于 2014-12-23 11:02:31
这可以作为
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如果不希望每月分组,那么从group子句中删除它,然后只使用年份。
注意,上面的查询是特定于mysql的。在标准中,当使用聚合函数选择某些列时,它们必须出现在he group by 子句中。。
https://stackoverflow.com/questions/27618851
复制相似问题