SELECT DISTINCT HAVING计算独特条件

时间:2012-11-06 19:59:17

标签: sql

我已经搜索过这方面的答案,但却找不到如何根据条件得到这个独特的记录集。我有一个包含以下示例数据的表:

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

我想创建一个查询,显示每个不同的Type + Color的唯一位置数,其中唯一位置的数量大于1,例如

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

请注意,{Apple,Red,1}没有出现,因为红苹果(芝加哥)只有一个位置。我想我已经有了这个(但也许有一个更简单的方法)。我正在使用:

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

Type, Color的唯一身份位数大于1时,如何为每个不同的Location创建另一个列出Type,ColorType,Color的查询?生成的记录集如下所示:

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

请注意,Apple, Red, Chicago没有出现,因为红苹果只有一个位置。谢谢!

2 个答案:

答案 0 :(得分:16)

使用COUNT(DISTINCT Location)并加入TypeColor上的子查询加入GROUP 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

答案 1 :(得分:3)

你可以写下你的第一个查询:

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

(如果您使用的是MySQL,则可以在UniqueLocations子句中使用别名having,但在许多其他系统上,别名尚不可用havingselect子句之前计算子句,在这种情况下,您必须重复两个子句的计数。)

对于第二个,有很多不同的方法可以写出来,这可能是一个:

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
  )