SELECT DISTINCT HAVING Count unique conditions

后端 未结 2 1341
無奈伤痛
無奈伤痛 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条回答
  •  旧时难觅i
    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

提交回复
热议问题