PDA

View Full Version : SQL COUNT(condition)?


rossco_2005
01-09-2010, 01:52 PM
Hi,

I have two queries:

SELECT COUNT(*) AS comments
FROM ng_comment
WHERE ng_comment.collectionid = 47

SELECT COUNT(*) AS comments2
FROM ng_comment
WHERE ng_comment.collectionid = 47
AND ng_comment.dateline <= 1262487011
Is there a way that I can combine these?
I was thinking something like:

SELECT COUNT(*) AS comments, COUNT(IF ng_comment.dateline <= 1262487011) AS comments2
FROM ng_comment
WHERE ng_comment.collectionid = 47
But I'm not sure what the syntax for this is in MySQL.

Any help? Thanks.

PS. I also posted this on vbulletin.com, but I think this forum is a bit busier than the programming discussion on vbulletin.com. (http://www.vbulletin.com/forum/showthread.php?336199-SQL-COUNT%28condition%29)

--------------- Added 1263058583 at 1263058583 ---------------

I figured it out for myself.
I used:

SELECT COUNT(*) AS totalcomments, COUNT(CASE WHEN ng_comment.dateline <= 1262487011 THEN 1 ELSE null END) AS newercomments
FROM ng_comment
WHERE ng_comment.collectionid = 47