2016-04-25 84 views
2

有人遞給我一個場景,具有尋找解決這個sql查詢

產品架構的更優雅的方式:

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

和查詢是

獲取製造商只生產一種產品類型和多個 模型。

輸出列應該是製造商和類型。

這就是我想出來的。

select distinct maker, type 
from Product 
where maker in (select maker 
       from Product 
       group by maker, type 
       having count(model) > 1 
       except 
       select maker 
       from 
       (
        select distinct maker, type 
        from Product 
       ) A 
       group by maker 
       having count(type) > 1) 

我知道這似乎不優雅的以任何方式,所以我想知道是否有人能想出一個更好的選擇和爲什麼它比上述的查詢更好地解釋。


編輯:請確保答案是僅僅兩列寬是

設備,類型

+1

能否請你添加一個標籤爲您的RDBMS引擎? – amphetamachine

+0

子查詢可以簡單地是一個GROUP BY,在HAVING中有條件。 – jarlh

回答

1

一種方法是使用existsnot exists

select distinct p.maker, p.type 
from product p 
where exists (select 1 
       from product p2 
       where p2.maker = p.maker and p2.type = p.type and p2.model <> p.model 
      ) and 
     not exists (select 1 
        from product p2 
        where p2.maker = p.maker and p2.type <> p.type 
       ); 

另一個版本使用顯式聚合:

select p.maker, p.type 
from product p 
where not exists (select 1 
        from product p2 
        where p2.maker = p.maker and p2.type <> p.type 
       ) 
group by p.maker, p.type 
having min(model) <> max(model); 

而且,爲了完整起見,這裏是只使用窗口功能的版本:

select p.model, p.type 
from (select p.*, 
      min(type) over (partition by maker) as mintype, 
      max(type) over (partition by maker) as maxtype, 
      row_number() over (partition by maker, type order by model) as seqnum, 
      count(*) over (partition by maker, type) as cnt 
     from product p 
    ) p 
where seqnum = 1 and 
     mintype = maxtype and 
     cnt > 1; 
1
select count(distinct model) as unique_model_count, 
     count(distinct type) as unique_type_count, 
     maker 
from Product 
group by maker 
having unique_type_count=1 and unique_model_count>1 
+0

_無限_這個「正確」的答案!但是,我認爲需要包括「製造商」和「類型」一個簡單的解決這裏顯示的內容。 (沒有嘗試過......)我不是100% - 確保可以按照「having」子句中所示使用列名,但可能必須在此重複「count()」表達式。 。 。? –

+0

正確的邏輯,但如果未指定的RDBMS在having子句中不允許別名,則可能會引發錯誤。 –

+0

@MikeRobinson。 。 。我認爲這不是正確的答案,因爲它不包含'type'。 –

2
SELECT maker, MIN(type) as type 
FROM Product 
GROUP BY maker 
HAVING COUNT(DISTINCT type) = 1 AND COUNT(DISTINCT model) > 1; 
+1

在大多數數據庫中,這將返回一個錯誤('type'不是開始彙總)。在MySQL中,它只會爲每個製造商返回一個「類型」。 –

+0

我知道,但問題是哪個製造商生產一種類型,所以我認爲它會好起來的 – Autor69