SELECT DISTINCT HAVING Count unique conditions

后端 未结 2 1316
無奈伤痛
無奈伤痛 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: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
      )
    

提交回复
热议问题