如何使用group by计算表中的Max(Count(Columnname))

时间:2012-08-26 08:40:08

标签: sql sql-server-2008 group-by having-clause

如何查找以下查询的数据

Original Source问题89

表格结构: 产品(制造商,型号,类型)

修改 Use sqlfiddle for schema

任务:
找出那些拥有最多模特的制造商 产品表以及模型数量最少的产品表。 输出:制造商,型号数量

有问题的提示是GROUP BYHAVINGIN

我尝试了各种方法来找到这个基本上我想出来的是我需要使用Max(COUNT(model))

结果应为

maker   qty 
A        7 --max
C        1 --min

我想出的一个解决方案是

select maker, count(ps.model) as Count from product as ps
group by ps.maker
having count(ps.model) in
(
select max(cnt) from (select count(model) as cnt from product group by maker)t
union
select min(cnt) from (select count(model) as cnt from product group by maker)t
)

还有其他办法。

2 个答案:

答案 0 :(得分:2)

你可以简单地......

SELECT *
FROM (
    SELECT TOP 1 maker, COUNT(*) C
    FROM product
    GROUP BY maker
    ORDER BY C DESC
) Q1
UNION
SELECT *
FROM (
    SELECT TOP 1 maker, COUNT(*) C
    FROM product
    GROUP BY maker
    ORDER BY C
) Q2;

......或者如果你喜欢CTE ......

WITH CTE AS (
    SELECT maker, COUNT(*) C
    FROM product
    GROUP BY maker
)
SELECT *
FROM (
    SELECT TOP 1 *
    FROM CTE
    ORDER BY C DESC
) Q1
UNION
SELECT *
FROM (
    SELECT TOP 1 *
    FROM CTE
    ORDER BY C
) Q2;

...正如此SQL Fiddle所示。

答案 1 :(得分:1)

如果您使用的是SQL Server 2008,则可以使用它来简化它:http://www.sqlfiddle.com/#!3/25ba8/7

with counts as
(
  select maker, count(ps.model) as Count from product as ps
  group by ps.maker
)
select cx.*
from counts cx
join
(
  select min(count) as lo, max(count) as hi
  from counts
) as hi_lo 
on cx.count = hi_lo.lo or cx.count = hi_lo.hi;