如何为第一列上具有重复项的行选择第二列?

时间:2011-05-15 01:15:39

标签: mysql sql string

我有一个包含两列的表格:

  • 国家

我想要一个包含所有City值的结果集。对于我想要包含国家/地区列的相同城市值的行。我想要的结果集的一个例子如下:

City
----------------
Chicago
New York
Toronto
London, Canada
London, England
Los Angeles

注意

兴趣点是“伦敦”的重复城市名称,包括逗号,空格和国家/地区名称以区分它们。

如何使用MySQL语句实现此目的?我使用group byhaving条款尝试了一些事情,但我无法得到我想要的结果。

5 个答案:

答案 0 :(得分:2)

使用:

  SELECT a.city AS city
    FROM YOUR_TABLE a
GROUP BY a.city
  HAVING COUNT(a.country) = 1
UNION ALL
 SELECT CONCAT(b.city, ', ', b.country) AS city
   FROM YOUR_TABLE b
  WHERE EXISTS (SELECT NULL
                  FROM YOUR_TABLE c
                 WHERE c.city = b.city
              GROUP BY c.city
                HAVING COUNT(c.country) > 1)
ORDER BY city

答案 1 :(得分:1)

您可以使用以下SQL语句,假设cityTable中的表名称

    SELECT cityTable.City  , cityTable.Country  FROM cityTable INNER JOIN ( SELECT City FROM cityTable GROUP BY City HAVING COUNT(City) > 1 ) as tempTable ON cityTable.City = tempTable.City

    SELECT City FROM Table GROUP BY City HAVING  COUNT(City) = 1 

第一个查询将为所有重复城市提供国家/地区名称,第二个查询将为所有不重复的城市提供仅城市名称。

答案 2 :(得分:1)

accepted answer完全可行。这是解决问题的另一种方法:

   SELECT CASE
          WHEN repeated IS NULL THEN city
          ELSE                       city || ', ' || country
          END AS city
LEFT JOIN (SELECT city AS repeated
             FROM cities
         GROUP BY 1
           HAVING COUNT(1) > 1) d
          ON cities.city = d.repeated

答案 3 :(得分:0)

这在MySQL中不起作用,它还不支持窗口化(AFAIK!),但是对于记录,在的RDBMS中,你可以做到

SELECT CASE WHEN (count(*) > 1) THEN (city || ', ' || country) ELSE city END
OVER (PARTITION BY city)
FROM city_table;

答案 4 :(得分:-1)

DELETE FROM table WHERE city IN (
SELECT city, 
 COUNT(city) AS NumOccurrences
FROM table
GROUP BY city
HAVING ( COUNT(city) > 1 )