Count & Group By Conflict
I'm having a conflict in the 开发者_JS百科following query:
SELECT COUNT(*) AS poststotal FROM posts GROUP BY category
The following query returns the poststotal containing the number of categories instead of the total posts count groupped by categories.
So:
TABLE: posts(title,category)
----------------------------
foo1 | art
foo2 | politic
foo2 | politic
foo3 | fun
Will return:
4
Instead of:
3 posts
How to deal with that?
/* get count for each category */
SELECT category, COUNT(*) AS poststotal FROM posts GROUP BY category;
your original query should return 3, it could be caused by whitespace stored in column category, try
/* verify */
select title, length(category) from posts;
/* ensure whitespace trimmed */
SELECT COUNT(*) AS poststotal FROM posts GROUP BY trim(category);
hmm, thanks, but i want to get the total number of all posts but only one post of each category :) also the categories are fully trimmed
is quite different from what you had described
select
*
from posts
group by category
/* the above will return single posts for each category */
I am still not sure if I understood your question 100%, but how about that?
SELECT COUNT(*)
FROM poststotal
WHERE category IN
(
SELECT category
FROM poststotal
GROUP BY category
HAVING COUNT(*) > 0
)
if you don't want the count to be grouped by categorys, don't groub by. do it like this:
SELECT COUNT(*) AS poststotal FROM posts
(it's that easy, i think i missunderstood your question... but i'll give it a try)
精彩评论