views:

50

answers:

3

let say i have one table, which have data like:

name       status
bob        single
bob        single
jane       null
tina       null
shane      married

i want if status "single or data null" it means single. so if data empty script can read it as single and can count together. so i can show result like:

Single     Married
3            1

i have tried with this and it doesnt work:

SELECT SUM(IF(status='single',1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table
A: 

If you know there are only 'single', 'married', and null as options, this will work:

SELECT SUM(IF(status!='married',1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table

Otherwise try

SELECT SUM(IF(status='single' OR status is null,1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table
JoshD
how to prevent i count double data?
klox
I'm not sure what you mean. This will not count any row twice because the conditions are complimentary.
JoshD
If you tried the query and still have issues, update the question with the new problems and the new query, and we can see what to do.
JoshD
A: 
SELECT SUM(IF(status='single' OR status IS NULL,1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table
armonge
how do i do to prevent double data like my edited question.
klox
+1  A: 

Use:

SELECT SUM(CASE WHEN x.status = 'single' OR x.status IS NULL THEN 1 ELSE 0 END) AS single,
       SUM(CASE WHEN x.status = 'married' THEN 1 ELSE 0 END) AS married
  FROM (SELECT DISTINCT
               t.name,
               t.status
          FROM YOUR_TABLE t) x
OMG Ponies
SUM(CASE WHEN x.status = 'single' OR status IS NULL THEN 1 ELSE 0 END) AS single,can i do like that?
klox
@klox: Yes, see updated answer
OMG Ponies