2012-11-06 51 views
11

我已經在此搜索了一個答案,但無法找到相當的方式如何根據條件獲取此不同的記錄集。我有下面的示例數據的表:SELECT DISTINCT HAVING計數的唯一條件

Type Color Location Supplier 
---- ----- -------- -------- 
Apple Green New York ABC 
Apple Green New York XYZ 
Apple Green Los Angeles ABC 
Apple Red  Chicago  ABC 
Apple Red  Chicago  XYZ 
Apple Red  Chicago  DEF 
Banana Yellow Miami  ABC 
Banana Yellow Miami  DEF 
Banana Yellow Miami  XYZ 
Banana Yellow Atlanta  ABC 

我想創建一個查詢,顯示了爲每個不同類型+顏色,其中的獨特位置的數量大於1,例如唯一的位置的計

Type Color UniqueLocations 
---- ----- -------- 
Apple Green 2 
Banana Yellow 2 

請注意{Apple,Red,1}沒有出現,因爲紅蘋果只有1個位置(芝加哥)。我想我有這個(但也許有一個更簡單的方法)。我使用的是:

SELECT Type, Color, Count(Location) FROM 
(SELECT DISTINCT Type, Color, Location FROM MyTable) 
GROUP BY Type, Color HAVING Count(Location)>1; 

如何創建另一個查詢,其中列出了Type, Color,並Location爲每個不同的Type,Color時的獨特位置爲Type,Color計數大於1?結果記錄看起來像:

Type Color Location 
---- ----- -------- 
Apple Green New York 
Apple Green Los Angeles 
Banana Yellow Miami 
Banana Yellow Atlanta 

注意Apple, Red, Chicago不會出現,因爲只有1對紅蘋果的位置。謝謝!

回答

13

使用COUNT(DISTINCT Location)並加入針對一個子查詢的TypeColorGROUP BYHAVING條款,你試圖使用他們將做的工作。

/* Be sure to use DISTINCT in the outer query to de-dup */ 
SELECT DISTINCT 
    MyTable.Type, 
    MyTable.Color, 
    Location 
FROM 
    MyTable 
    INNER JOIN (
    /* Joined subquery returns type,color pairs having COUNT(DISTINCT Location) > 1 */ 
    SELECT 
     Type, 
     Color, 
     /* Don't actually need to select this value - it could just be in the HAVING */ 
     COUNT(DISTINCT Location) AS UniqueLocations 
    FROM 
     MyTable 
    GROUP BY Type, Color 
    /* Note: Some RDBMS won't allow the alias here and you 
     would have to use the expanded form 
     HAVING COUNT(DISTINCT Location) > 1 
    */ 
    HAVING UniqueLocations > 1 
    /* JOIN back against the main table on Type, Color */ 
) subq ON MyTable.Type = subq.Type AND MyTable.Color = subq.Color 

Here is a demonstration

+0

非常感謝邁克爾! – vfxdev

3

你可以寫你的第一個查詢,因爲這:

Select Type, Color, Count(Distinct Location) As UniqueLocations 
From Table 
Group By Type, Color 
Having Count(Distinct Location) > 1 

(如果你使用MySQL,你可以使用別名UniqueLocationshaving條款,但在許多其他系統的別名不可用,因爲having子句在select子句之前被評估,在這種情況下,您必須重複對兩個子句的計數)。

而對於第二個,有編寫許多不同的方式,這可能是一個:

Select Distinct Type, Color, Location 
From Table 
Where 
    Exists (
    Select 
     * 
    From 
     Table Table_1 
    Where 
     Table_1.Type = Table.Type 
     and Table_1.Color = Table.Color 
    Group By 
     Type, Color 
    Having 
     Count(Distinct Location) > 1 
) 
+0

非常感謝fthiella! – vfxdev

+0

第一位不起作用。它不識別「UniqueLocations」 –

+0

@EliPerpinyal你正在使用哪些DBMS? – fthiella