选择在同一列上有两个计数

时间:2010-09-30 12:38:57

标签: sql mysql select group-by

我有两个选择查询:

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

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

如何编写一个查询来选择

SELECT MONTH(date) AS month, 
       count(DISTINCT ip) [ for field = 1], 
       count(DISTINCT ip) [ for field = 2]

1 个答案:

答案 0 :(得分:5)

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