Count and Avg the number of records in MySQL
Hey guys, I need some help with this. I have a table with about 100k records. Each row is referenced by an ID. Here is an example
Keyword | Domain | Page | UserID
Hello | www.example.com | 1 | 994
World | www.example.com | 1 | 994
Genius | www.example.com | 1 | 994
Example map | www.example.com | 2 | 994
Hello | www.example.com | 1 | 994
demo0 | www.test.com | 1 | 994
demo1 | www.test.com | 2 | 994
demo2 | www.test.com | 2 | 994
demo3 | www.test.com | 3 | 994
wonderful | www.mysql.com | 1 | 997
wonder | www.mysql.com | 1 | 997
SOFLOW | www.mysql.com | 1 | 997
What I want to see 开发者_JAVA技巧is how many (single number) keywords appear on Page 1, 2 or 3 for a user.
Here is an example output:
User | Domain | Total KW | #Page 1 | #Page 2 | # Page3
994 | www.example.com | 5 | 3 | 1 | 0
994 | www.test.com | 4 | 1 | 2 | 1
I know I can do this in PHP, but is there any way to do this in MySQL? I can get the avg and the count but I cant get what I want :(
Any help is much appreciated. Thanks.
SELECT User, Domain, COUNT(Page),
SUM(IF(Page=1, 1, 0)) AS Page1,
SUM(IF(Page=2, 1, 0)) AS Page2,
SUM(If(Page=3, 1, 0)) AS Page3
FROM table
GROUP BY User, Domain
This would get tedious if there's more than just these 3 "pages". At that point you should just group on the page as well, count them normally without the SUM stuff, and then do the multi-column formatting in your application.
精彩评论