2015-11-02 75 views
2

我有一個查詢我正在嘗試擴展並遇到了障礙。我想要做的是返回包含計數,總計和平均值的數據,這些數據是圍繞共享但不共享的屬性提供的。MySQL:使用何時總和/平均值共享和不共享?

我有它非常接近,但返回NULL和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)     | 
+--------+------------------+------------------+------------------------+---------------------------+ 

取而代之的將是沒有被「橙色」和提交的不共享的屬性和共享屬性的總量「橙」

我在Mac上的優勝美地運行MySQL 5.6 。

理想情況下,我想實現這個沒有子選擇,但如果它是必需的,沒有選擇,那麼我想更多地瞭解這一點。

+0

的HAVAING子句旨在用於聚合函數的條件。改爲在WHERE子句中放置水果='橙色'。 – jarlh

回答

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;  
+1

太棒了..謝謝!! – lcm