tags:

views:

81

answers:

4

Hi, I currently am returning a table that looks like this:

Country  Result
------   -----
Japan    sunk
Japan    sunk
USA      ok
USA      ok

with country and result being the column names

Id like to know how many times japan and sunken show up? So the resulting query I am trying to achieve is:

country      numSunk
-------      ------
Japan        2
USA          0

I've tried grouping or doing a where result="sunk" but I keep getting errors. Any thoughts? Thanks.

+4  A: 

This should work:

SELECT country, COUNT(*) AS sunk
FROM table
WHERE result = "sunk"
GROUP BY country

Edit: if you want 0-rows then you can do:

SELECT country, SUM(IF(result = "sunk", 1, 0)) AS sunk
FROM table
GROUP BY country
Greg
This query will only return a single row: [Japan, 2], as no USA rows match the filter criteria.
pmarflee
Hmmm...that only appears to return Japan and 2. I still need to get USA 0.
Phillip Whisenhunt
I've edited to give USA 0
Greg
awesome. Thanks.
Phillip Whisenhunt
A: 
select country, count(country)
...
where result = "sunk"
group by country

Assuming this is a SQL query

Babak Naffas
This query will return only 1 row [Japan, 2]. Grouping is applied after filtering, so as no USA rows match the filter criteria, only the Japan rows will remain for grouping.
pmarflee
+3  A: 
SELECT country, COUNT(CASE result WHEN 'sunk' then 1 ELSE NULL END) as numSunk
FROM myTable
GROUP BY country

The count will only be incremented when the result is 'sunk'.

pmarflee
Wouldn't ELSE 0 work better?
Guvante
@Guvante: No, that won't work. We need to use NULL when result <> 'sunk' so that the count is not incremented. If we were to use 0 when result <> 'sunk' then the aggregate function would need to be SUM(), not COUNT().
pmarflee
A: 

Try something like this:

SELECT country, count(*) numSunk
FROM table
WHERE result = 'sunk'
GROUP BY country
UNION
SELECT DISTINCT country, 0 
FROM table t
WHERE NOT EXISTS
  (SELECT 1 FROM table WHERE t.country = country AND result = 'sunk')

The first SELECT gives you all the countries with a sunk result along with the sunk count. The unioned second SELECT gives you all the countries that have no sunk result.

Phil Ross