Skip to content
Advertisement

Get a count of individual instances of a value in MySQL

I have a table with two fields, inbound and outbound, both of which are text values. I want to get all a count of all instances of a specific value in either or both of those columns.

Here’s an example of the schema with some values and my query:

CREATE TABLE widgets (
  id int(5) auto_increment,
  inbound varchar(200),
  outbound varchar(200),
  event_name varchar(255),
  start_time int(11),
  primary key(id)
  );

  INSERT INTO widgets values (NULL, 'my_widget', 'other_widget', 'STARTED', unix_timestamp());
  INSERT INTO widgets values (NULL, 'my_widget', 'my_widget', 'STARTED', unix_timestamp());
  INSERT INTO widgets values (NULL, 'my_widget', 'my_widget', 'STARTED', unix_timestamp());

SELECT count(*)
            FROM (
                SELECT inbound, outbound, event_name
                FROM `widgets`
                ORDER BY `start_time` DESC
                LIMIT 10000
            ) AS t
            WHERE
              (t.`inbound` = 'my_widget'
                OR
                t.`outbound` = 'my_widget'
              )
            AND event_name != 'FINISHED'

Here’s an SQL fiddle with the schema and my current query

Currently I’m getting a count of 3 appearances of my_widget, however I want to count all 5 appearances of my_widget

Advertisement

Answer

You can do something like this with case statement, here is the demo.

select
  sum(total) as total
from
(
  select
    sum(case when inbound = 'my_widget' then 1 else 0 end) as total
  from widgets
  where event_name <> 'FINISHED'
  union all
  select
    sum(case when outbound = 'my_widget' then 1 else 0 end) as total
  from widgets
  where event_name <> 'FINISHED'
) t

Output:

*-------* 
| total |
*-------*
|    5  |
*-------*
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement