简体   繁体   中英

Mysql sum of field values - count , with group by , order by , limit function

I have Table user_views

My Tablet Sample data

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

I want the total count of the user visited this product

My Query

"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"

But the output is showing only one count

OUTPUT

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

EXPECTED OUTPUT IS

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

You should be using sum aggregate function instead of count which will count number of rows. So your query should be something like:

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

Try this:

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() always returns the number of items, not the sum of values. So use SUM() .

"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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM