views:

35

answers:

1

I have two select queries:

SELECT MONTH(date) AS month, count(DISTINCT ip) 
FROM table_name WHERE field = 1 GROUP BY month

and

SELECT MONTH(date) AS month, count(DISTINCT ip) 
FROM table_name WHERE field = 2 GROUP BY month

how can I write one query to select

SELECT MONTH(date) AS month, 
       count(DISTINCT ip) [ for field = 1], 
       count(DISTINCT ip) [ for field = 2]
+3  A: 
SELECT MONTH(date) AS month, 
       count(DISTINCT case when field = 1 then ip end) as f1,
       count(DISTINCT case when field = 2 then ip end) as f2
FROM table_name 
WHERE field in (1,2)
GROUP BY month
Martin Smith
Thank I didn't know about `case when .. then` systax.
jcubic