2012-08-26 54 views
1

(計數(列名)),如何找到數據下面的查詢如何使用GROUP BY來計算最大表

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 
) 

有沒有其他辦法。

+0

@marc_s usign http://www.sql-ex.ru練習在哪裏我得到了這個問題。所以不能說數據庫,但這是一個簡單的RDBMS問題 –

+0

你也可以練習你的SQL技能,並檢查它是否與RDBMS無關,試試這個:http://www.sqlfiddle.com/ –

+0

@MichaelBuen:對於這個在開始練習之前需要創建全新的數據集。但是,sql-ex提供了預建數據庫來練習選擇查詢。 –

回答

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; 
+0

剛剛添加[SqlFiddle](http://www.sqlfiddle.com/#!3/25ba8/1)。模式有點不同。我沒有預先計算的數量。它需要在製造商的基礎上進行計算。 –

+0

謝謝..我沒想到這個解決方案。相反,我想用TOP 1。 –

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; 

...或者,如果你喜歡的熱膨脹係數...

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