使用count()和group by麻烦

时间:2014-08-25 14:16:54

标签: sql count group-by

我有一个名为Products的表,看起来像:

maker      model   type
---------- -------  -----
A          1232      PC
A          1233      PC
A          1276      Printer
A          1401      Printer
A          1408      Printer
A          1298      Laptop
A          1752      Laptop
B          1121      PC
B          1750      Laptop
C          1321      Laptop
D          1433      Printer
D          1288      Printer
E          1260      PC
E          1434      Printer
E          2112      PC
E          2113      PC

我需要让制造商生产超过1个型号,但模型应该是相同的类型......这里应该是maker = D and Type = Printer

我花了整整一天使用计数(模型)> 1和计数(类型)= 1等等。没有任何作用。

4 个答案:

答案 0 :(得分:2)

SELECT maker,
       MIN(type) AS type
FROM Products
GROUP BY maker
HAVING COUNT(DISTINCT type) = 1
       AND COUNT(DISTINCT model) >1

答案 1 :(得分:2)

如果您想确定makermodel多个type,那么您可以使用GROUP BYHAVING来获取结果:

select maker
from products
group by maker
having count(distinct model) > 1 -- more than one model
  and count(distinct type) = 1   -- same type

请参阅SQL Fiddle with Demo如果您要为每个maker返回所有内容,请使用

select p.maker, p.model, p.type
from products p
where maker in (select maker
                from products t
                group by maker
                having count(distinct model) > 1
                  and count(distinct type) = 1);

请参阅Demo

答案 2 :(得分:1)

select distinct maker, type
from products t1
where exists (
    select 1 from products t2
    where t1.maker = t2.maker
    and t1.model <> t2.model
    and t1.type = t2.type
) and not exists (
    select 1 from products t2
    where t2.maker = t1.maker
    and t2.type <> t1.type
)

答案 3 :(得分:1)

With TempTable
AS(
    SELECT
        Maker ,Count(DISTINCT type) Count1,Count(model) as mcount
    FROM
        Products 
    GROUP BY
        Maker
    HAVING Count(DISTINCT type)=1
)

Select a.Maker from TempTable a
Where a.mcount IN (Select MAX(mcount) from TempTable)