MySQL:使用何时汇总/平均值共享而不共享?

时间:2015-11-02 09:13:48

标签: mysql sql

我有一个问题,我正在尝试扩展并遇到障碍。我想要做的是返回行,其中包含围绕共享和不共享的属性提供的数据的计数,总和和平均值。

我非常接近但是返回空值和0,我需要查看数据。

让我解释一下......但如果我需要澄清,请告诉我。

首先是我的表:

CREATE TABLE `fruits` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `fruit` varchar(11) DEFAULT NULL,
  `fruit_attribute` varchar(11) DEFAULT '',
  `submissions` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

INSERT INTO `fruits` (`id`, `fruit`, `fruit_attribute`, `submissions`)
VALUES
    (1,'Orange','tough peel',59),
    (2,'Lemon','tough peel',70),
    (3,'Orange','citrus',100),
    (4,'Orange','juice',90),
    (5,'Lemon','juice',75),
    (6,'Lemon','tart',35),
    (7,'Lemon','citurs',65),
    (8,'Orange','breakfast',110),
    (9,'Lemon','lemonaid',120),
    (10,'Orange','florida',50);

接下来,我的查询:

SELECT ft.fruit,  
       COUNT(distinct ft1.fruit_attribute) As att_shared_lemon,
       SUM(CASE WHEN ft1.fruit_attribute IS NULL THEN 1 ELSE 0 END) As not_shared_lemon,
       SUM(CASE WHEN ft1.fruit_attribute IS NOT NULL THEN ft.submissions END) as sum_shared_submissions, 
       SUM(CASE WHEN ft1.fruit_attribute IS NULL THEN ft.submissions END) as sum_notshared_submissions 
       FROM fruits  ft LEFT JOIN
     fruits ft1
     ON ft.fruit_attribute = ft1.fruit_attribute and ft1.fruit = 'Orange'
GROUP BY ft.fruit
having fruit='Orange'
ORDER BY att_shared_lemon desc;

这是上面的SQL小提琴:

http://sqlfiddle.com/#!9/86e863/12

所需的输出不包括下面的0和Null值:

+--------+------------------+------------------+------------------------+---------------------------+
| fruit  | attr_shared_orange | attr_not_shared_orange| sum_shared_submissions | sum_notshared_submissions |
+--------+------------------+------------------+------------------------+---------------------------+
| Orange |                5 |                0 |                    409 | (null)                    |
+--------+------------------+------------------+------------------------+---------------------------+

相反,将会有' Orange'未分享的属性总数。以及未与' Orange'

共享的属性的提交总和

我在mac Yosemite上运行mysql 5.6。

理想情况下,我希望在没有子选择的情况下实现这一点,但如果需要并且没有选项,那么我想了解更多。

1 个答案:

答案 0 :(得分:2)

我认为这里的连接逻辑存在一个小问题,你想要对水果之间的链接进行求和,但是你的查询确保你总是将橘子加入橙子,因此永远不会有不属于的属性分享:

ON ft.fruit_attribute = ft1.fruit_attribute and ft1.fruit = 'Orange'

请尝试此查询:

SELECT ft.fruit,  
       COUNT(distinct ft1.fruit_attribute) As att_shared_lemon,
       SUM(CASE WHEN ft1.fruit_attribute IS NULL THEN 1 ELSE 0 END) As not_shared_lemon,
       SUM(CASE WHEN ft1.fruit_attribute IS NOT NULL THEN ft.submissions END) as sum_shared_submissions, 
       SUM(CASE WHEN ft1.fruit_attribute IS NULL THEN ft.submissions END) as sum_notshared_submissions 
       FROM fruits  ft 

       LEFT JOIN fruits ft1
        ON ft.fruit_attribute = ft1.fruit_attribute and ft.fruit = 'Orange'
        AND ft1.fruit != ft.fruit

WHERE ft.fruit='Orange'     

GROUP BY ft.fruit
ORDER BY att_shared_lemon desc;