Mysql字段值的总和 - count,with group by,order by,limit function

时间:2014-12-13 07:26:13

标签: mysql

我有Table user_views

我的平板电脑样本数据

Id | product_id | category | user_id |  sitename|   price | click_count | created_date
 1     10          watch     102          ebay       820     1            2014-08-18 13:56:05
 2     10          watch     102          amazon     750     1            2014-08-19 13:56:05
 3     10          watch     102          amazon     740     1            2014-08-19 18:00:05
 4     10          watch     102          ebay       940     1            2014-08-25 08:00:00
 5     10          watch     102          amazon     640     5            2014-08-25 08:10:10
 6     10          watch     102          ebay       580     3            2014-09-25 18:10:10
 7     10          watch     102          amazon     980     5            2014-10-05 12:20:40

我想要访问此产品的用户总数

我的查询

"select Id , proudct_id , category , user_id , count(click_count) as cnt from user_view where user_id =102 group by product_id order by rand() limit 0,10"

但输出只显示一个计数

输出

 Id | product_id | category | user_id | cnt
  1     10          watch      102       1         

预期输出

 Id | product_id | category | user_id |  cnt  
  1     10         watch       102       17  

3 个答案:

答案 0 :(得分:1)

你应该使用sum aggregate函数而不是count来计算行数。所以你的查询应该是这样的:

  select Id , product_id , category , user_id , SUM(click_count) as sum ...

答案 1 :(得分:-1)

试试这个:

select Id , proudct_id , category , user_id , SUM(click_count) as cnt
from user_view
 where user_id =102
order by rand()
limit 0,10
group by product_id

COUNT()始终返回项目数,而不是值的总和。因此,请使用SUM()

答案 2 :(得分:-1)

"select Id , proudct_id , category , user_id , count(click_count) as cnt from user_view where user_id =102 group by user_id, product_id order by rand() limit 0,10"