SQL查询输出的项目是否共享相同的属性?

时间:2015-07-16 07:51:00

标签: mysql sql

所以说我有五个水果,一个是重点,另外四个是长期农业的兴趣。这些成果当然有很多属性,一些共享份额和其他属性对每种水果都是独一无二的。

以下SQL查询及其变体可以确定共享哪些属性。我能够从[here] [1]及时提供的答案中得到我想要的东西,但仍在挖掘以获得我需要的报告。

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

但是,我无法确定如何确定Apple未共享的属性(例如)。

我正在寻找的理想输出看起来像这样:

Fruit | Shared w/ Apple | Not Shared w/ Apple
---------------------------------------------
Orange       1                       5
Banana       0                       8
Pear         6                       2
Plum         2                       9

提前感谢您以这种方式发送的任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以自行加入FRUIT_TABLE

SELECT ft1.FRUIT_NAME AS Fruit,
    SUM(CASE WHEN ft2.ATTRIBUTE IS NOT NULL THEN 1 ELSE 0 END) As 'Shared with Apple',
    SUM(CASE WHEN ft2.ATTRIBUTE IS NULL THEN 1 ELSE 0 END) As 'Not Shared with Apple'
FROM FRUIT_TABLE ft1 LEFT JOIN
(
    SELECT ATTRIBUTE, FRUIT_NAME
    FROM FRUIT_TABLE ft
    WHERE ft.FRUIT_NAME = "Apple"
) ft2
ON ft1.ATTRIBUTE = ft2.ATTRIBUTE
GROUP BY ft1.FRUIT_NAME