0

I am counting clicks per category of ads. I am curently passing category to function, I have 10 cats, so I am calling this function 10 times to get number of clicks for each category. So i am trying to figure out is it possible to do in one query. Just started with mysql This is my code:

SELECT SUM(clicks) AS 'clicks' FROM wp_cb_ads_manager WHERE category = '.$cat.'

and this gives me

Array ( [0] => stdClass Object ( [clicks] => 11 ) ) 

Is it possible to do this on one query, so to retrieve SUM per each category in array. Here is the screen of how 2 tables looks like:

http://awesomescreenshot.com/00018kly6d http://awesomescreenshot.com/06418kltcc

In first i keep list of categories, and in second I keep ads where one field is used to check in which category is ad.

1
  • A bit unclear, you may want to add the schema to your question instead of linking to external images. Commented May 4, 2013 at 18:37

3 Answers 3

2

If I'm reading your screenshots correctly, this will display the sum grouped by category;

SELECT category, SUM(clicks) AS clicks 
FROM wp_cb_ads_manager 
GROUP BY category
Sign up to request clarification or add additional context in comments.

2 Comments

Thank You! Worked like a charm. Still learning mysql, if i want to sum also one more data like impressions, should i just do: ... SUM(clicks) AS clicks, SUM(impressions) AS 'impressions' FROM....
@GoranJakovljevic Yes, as long as you want to group them all by the same thing (ie category) that will work well.
1

Try this query

SELECT SUM(clicks) AS 'clicks', count(*), category  FROM wp_cb_ads_manager group by category

It works perfectly.

Refer to this

MySQL SUM when using GROUP BY not working

Comments

0

You can achive this by group by statement

SELECT SUM(clicks) AS 'clicks', category FROM wp_cb_ads_manager group by category

Your result set will have sum of clicks against each catrgoty

  clicks   | category
    3      |  goan
    5      |  roan
    8      |  mone

and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.