3

我坐了几个小时试图解决特定问题,但我无法得到它。最后,我决定把它贴在这里。这里有一些记录,

╔════════╦════════════╦═════════╦══════════════════╗
║ AUTOID ║ PERSONNAME ║ FLOWER  ║ Other columns... ║
╠════════╬════════════╬═════════╬══════════════════╣
║      1 ║ Alex       ║ Rose    ║                  ║
║      2 ║ Rene       ║ Rose    ║                  ║
║      3 ║ Rene       ║ Jasmin  ║                  ║
║      4 ║ Darwin     ║ Rose    ║                  ║
║      5 ║ Alex       ║ Rose    ║                  ║
║      6 ║ Darwin     ║ Jasmin  ║                  ║
║      7 ║ Alex       ║ Rose    ║                  ║
║      8 ║ Rene       ║ Jasmin  ║                  ║
║      9 ║ Hello      ║ World   ║                  ║
║     10 ║ Hello      ║ World   ║                  ║
╚════════╩════════════╩═════════╩══════════════════╝

我怎样才能得到这个结果,他/她的所有记录中只有一种花的人

╔════════════╦════════════╗
║ PERSONNAME ║ FLOWERNAME ║
╠════════════╬════════════╣
║ Alex       ║ Rose       ║
║ Hello      ║ World      ║
╚════════════╩════════════╝

我尝试过的最好的查询是下面的这个查询,但仍然无法正常工作。

SELECT  DISTINCT t1.PersonName, t1.Flower
FROM    TableName t1 
        INNER JOIN
        (
            SELECT  personname, COUNT(DISTINCT flower) totals
            FROM    tableName
            GROUP   BY personname, Flower
        )  t2 ON t1.personname = t2.personname and
                    t2.totals = 1

任何的想法?

4

2 回答 2

4

您可以使用GROUP BY子句,HAVING子句和COUNT()这个问题,无需加入子查询

SELECT  PersonName, MAX(Flower) flowerName
FROM    TableName
GROUP   BY PersonName
HAVING  COUNT(DISTINCT Flower) = 1
于 2013-02-01T17:29:15.977 回答
0

或者,因为总是有不止一种方法可以给猫剥皮……

SELECT x.*
  FROM tablename x
  LEFT
  JOIN tablename y
    ON y.personname = x.personname
   AND ((y.flower <> x.flower)
    OR  (y.flower = x.flower AND y.autoid < x.autoid))
 WHERE y.autoid IS NULL;
于 2013-02-01T18:15:07.490 回答