在单个表中显示重叠行的SQL查询?

时间:2015-07-15 23:46:28

标签: mysql sql

我一直在谷歌和SO搜索这个问题的答案但是很难过。我甚至不确定我是否正确地问它,但我会在这里给它最好的拍摄:

我的数据:

Fruit  | Attributes
-------------------
Apple  | Dark Red
Apple  | Green
Apple  | Yellow
Apple  | Light Red
Apple  | Greenish Yellow
Apple  | Dark Yellow
Apple  | Brown
Banana | Yellow
Banana | Greenish Yellow
Banana | Dark Yellow 
Banana | Yellow 
Banana | Brown
Banana | Red
Banana | Black

我想要做的是运行一个查询,输出重叠的所有水果(在这种情况下只是苹果和香蕉)的多少属性。

希望我已经清楚了......如果我需要澄清,请告诉我。

1 个答案:

答案 0 :(得分:2)

这样的东西?

SELECT DISTINCT ATTRIBUTE, FRUIT 
FROM FRUIT_TABLE
WHERE ATTRIBUTE IN (
    SELECT ATTRIBUTE
    FROM FRUIT_TABLE
    GROUP BY ATTRIBUTE
    HAVING COUNT(DISTINCT FRUIT_NAME) > 1 )
ORDER BY ATTRIBUTE, FRUIT_NAME

我以类似的方式与City和State一起尝试过它并且它起作用了:

SELECT DISTINCT CITY, STATE 
FROM ADDRESS
WHERE CITY IN (
    SELECT CITY
    FROM ADDRESS
    GROUP BY CITY
    HAVING COUNT(DISTINCT STATE) > 1)
ORDER BY CITY, STATE    
  • BATH NB
  • BATH ON
  • BEDFORD NS
  • BEDFORD QC
  • BRANDON MB
  • BRANDON MT
  • Brampton NB
  • Brampton ON

......等等

SELECT ATTRIBUTE, COUNT(*) FROM (
    SELECT DISTINCT ATTRIBUTE, FRUIT 
    FROM FRUIT_TABLE
    WHERE ATTRIBUTE IN (
        SELECT ATTRIBUTE
        FROM FRUIT_TABLE
        GROUP BY ATTRIBUTE
        HAVING COUNT(DISTINCT FRUIT_NAME) > 1 )
        ORDER BY ATTRIBUTE, FRUIT_NAME ) AS RESULTS
GROUP BY ATTRIBUTE