Thursday Jun 25, 2009  2

sql: COUNT() with conditions

Here’s the skinny, I basically have to periodical parse raw data and save their totals on another table for easier access. In this scenario I basically need to count all raw and unique IP’s from a table and mark them; so when I parse the data again I don’t have to count the values I already totaled.

Below is a sample table containing some data. My goal is to get a count of the unique IP’s that are counted and the total number of raw ip’s that are not counted. This is a much simpler example of what I am trying to achieve on my script, but I hope you get the gist.

+----+---------------+---------+
| id | ip            | counted |
+----+---------------+---------+
|  1 | 127.0.0.1     |       0 |
|  2 | 127.0.0.1     |       1 |
|  3 | 192.168.1.100 |       0 |
|  4 | 192.168.1.100 |       1 |
|  5 | 10.0.0.1      |       0 |
|  6 | 10.0.0.1      |       0 |
+----+---------------+---------+

Now here’s the query:

SELECT ip,
	COUNT(CASE WHEN counted=0 THEN id ELSE NULL END) AS not_counted,
	COUNT(DISTINCT CASE WHEN counted=1 THEN ip ELSE NULL END) AS is_counted
	FROM test
	GROUP BY ip;
+---------------+-------------+------------+
| ip            | not_counted | is_counted |
+---------------+-------------+------------+
| 10.0.0.1      |           2 |          0 |
| 127.0.0.1     |           1 |          1 |
| 192.168.1.100 |           1 |          1 |
+---------------+-------------+------------+
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Technorati
  • Twitter

{ 2 comments… read them below or add one }

1 Gongolo November 17, 2009 at 5:46 pm

Very very useful!
Case into count … magic!

Reply

2 ABitSmart January 13, 2010 at 12:02 am

Thank you. Works perfect !

Reply

Leave a Comment

Previous post:

Next post: