需要SQL查询来查找计数

时间:2014-08-08 07:09:20

标签: sql aggregate

Household          Individual
101                      11
101                      12
101                      13
101                      14
101                      15
102                      1
102                      2
102                      3
102                      4

我需要一个SQL查询来获得超过4个人的家庭数量。在上表中,只有家庭101有超过4个人。因此摘录应为1

8 个答案:

答案 0 :(得分:1)

SELECT COUNT(*)
FROM 
(
    SELECT Household 
    FROM   TableName 
    GROUP BY Household 
    HAVING COUNT(Household) > 4
) AS T        

答案 1 :(得分:1)

也许是这样的:

SELECT COUNT(Household)
FROM
(
 SELECT Household
 FROM TABLE1
 GROUP BY Household
 HAVING Count(Household) > 4
) Tmp

<强> FIDDLE DEMO

答案 2 :(得分:0)

SELECT Household, count(Household) as cnt FROM {{TABLE}} 
GROUP BY Household
WHERE cnt > 4

答案 3 :(得分:0)

SELECT household FROM YourTable
GROUP BY household
HAVING COUNT(DISTINCT individual) > 4

答案 4 :(得分:0)

如果我理解你的问题,这应该给你正确的价值(1)。

select count(*) from (select Household  from table group by Household  having count(*)>4)

答案 5 :(得分:0)

select 
    distinct Household
from 
    Table_2
where
    Individual > 4

结果将是101。

如果您需要计数(不是上面的数字),那么

select 
    COUNT (Household) as E1
from 
    Table_2
where
    Individual > 4

答案 6 :(得分:0)

初步答复

当然,演示需要选择SQL实现,我的选择是T-SQL;但该解决方案非常适用于其他SQL实现:

declare @householdInfo table (Household int, Individual int);

insert into @householdInfo (Household, Individual)
select 101, 11
union
select 101, 12
union
select 101, 13
union
select 101, 14
union
select 101, 15
union
select 102, 1
union
select 102, 2
union
select 102, 3
union
select 102, 4;

--select * from @householdInfo; -- FORNOW: for sanity checking

-- NOTE: what you basically need - that yields 1 like you expect
select COUNT(*)
from (
    select Household, COUNT(Individual) IndividualCount
    from @householdInfo
    group by Household
    having COUNT(Individual) > 4) s;

重要的部分是你需要:

  1. 在内部查询中选择COUNTIndividual
  2. COUNT的{​​{1}}分为Individual个值。
  3. 使用等效于Household - WHERE的汇总来过滤内部查询的结果(即HAVING)。
  4. 在外部查询中选择最终的> 4
  5. 后继

    @VigneshKumar和@GiannisParaskevopoulos提出了一个很好的观点 - 从技术上讲,你在内部查询的列列表中不需要COUNT

    另一个(丑陋的)微妙存在于野外,可能适用于您的情况,并且不仅需要COUNT内部查询(COUNT(Individual)子句),还需要进一步利用< em> distinct count :

    HAVING

    从您提供的示例数据中进行简单的更改......

    select COUNT(Household) -- yes, prefer Household over * for clarity
    from (
        select Household
        from @householdInfo
        group by Household
        -- distinct added if duplicates are an issue
        having COUNT(distinct Individual) > 4) s;
    

    ...使区别(双关语)明确(即我提供的第一个查询在这种情况下会产生2,而我提供的第二个查询仍然会产生1)。

答案 7 :(得分:0)

我认为你需要:

SELECT COUNT(Household) AS HouseholdsWithMoreThan4Individuals
FROM (
    SELECT Household
    FROM [MytTable]
    GROUP BY Household
    HAVING COUNT(Individual) > 4) Res;

在这种情况下,结果将是1 - 您需要的结果 - 因为只有一个家庭拥有超过4个人。

您需要执行两项操作:首先,您需要获得超过4个人的所有家庭的列表。之后,您需要计算这些家庭。你需要注意不要多次计算任何家庭。