通过单一查询使用多个组

时间:2013-04-04 09:59:12

标签: mysql sql group-by

我有2个查询来获取count = 1且count = 2的家庭数。

SELECT Name, count(*) as c FROM Tablename GROUP BY HOUSE_NO HAVING c<=1;


 SELECT Name, count(*) as c FROM Tablename GROUP BY  HOUSE_NO HAVING c>=2 and c<=4;

但我需要将这些查询组合成单个查询。喜欢

         count1                          count2
  nooffamiliesHavingcount = 1        nooffamiliesHavingcount = 2

请帮助我......提前致谢..

2 个答案:

答案 0 :(得分:2)

SELECT CASE WHEN c <= 1 THEN "<=1"
            WHEN c BETWEEN 2 and 4 THEN "2-4"
       END familysize,
       COUNT(*) nooffamilies
FROM (SELECT Name, count(*) c
      FROM Tablename
      GROUP BY Name) x
GROUP BY familysize
HAVING familysize IS NOT NULL

FIDDLE

答案 1 :(得分:2)

您需要将您的第一个计数放入子查询中:

SELECT  COUNT(CASE WHEN C = 1 THEN 1 END) AS nooffamiliesHavingcount1,
        COUNT(CASE WHEN C = 2 THEN 1 END) AS nooffamiliesHavingcount2
FROM    (   SELECT  COUNT(*) AS C
            FROM    TableName
            GROUP BY House_No
        ) t
WHERE   c IN (1, 2);

修改

如果你需要计算你的计数范围,你可以使用它:

SELECT  COUNT(CASE WHEN C <= 1 THEN 1 END) AS nooffamiliesHavingcount1,
        COUNT(CASE WHEN C BETWEEN 2 AND 4 THEN 1 END) AS nooffamiliesHavingcount2,
        COUNT(CASE WHEN C > 4 THEN 1 END) AS nooffamiliesHavingcount3
FROM    (   SELECT  COUNT(*) AS C
            FROM    TableName
            GROUP BY House_No
        ) t

<强> Example on SQL Fiddle