SELECT DISTINCT HAVING Count unique conditions

后端 未结 2 1315
無奈伤痛
無奈伤痛 2021-02-05 07:55

I\'ve searched for an answer on this but can\'t find quite how to get this distinct recordset based on a condition. I have a table with the following sample data:



        
相关标签:
2条回答
  • 2021-02-05 08:00

    Use a COUNT(DISTINCT Location) and join against a subquery on Type and Color The GROUP BY and HAVING clauses as you have attempted to use them will do the job.

    /* 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 讨论(0)
  • 2021-02-05 08:23

    You could write your first query as this:

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

    (if you're using MySQL you could use the alias UniqueLocations in your having clause, but on many other systems the aliases are not yet available as the having clause is evaluated before the select clause, in this case you have to repeat the count on both clauses).

    And for the second one, there are many different ways to write that, this could be one:

    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 讨论(0)
提交回复
热议问题