Im working on an SQL query that have almost where I want it. I just want to add two more columns for the average submissions for each of the "attributes_share_lemon" and "attribites_not_shared_lemon".
Here is the SQL fiddle that I was working on here:
http://sqlfiddle.com/#!9/6ea5d8/8
Here is the create and the insert:
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`)
);
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);
My query:
SELECT ft1.fruit, ft1.submissions,
SUM(CASE WHEN ft2.fruit_attribute IS NOT NULL THEN 1 ELSE 0 END) As attributes_shared_lemon,
SUM(CASE WHEN ft2.fruit_attribute IS NULL THEN 1 ELSE 0 END) As attributes_not_shared_lemon
FROM fruits ft1 LEFT JOIN
(
SELECT ft.fruit, ft.fruit_attribute, ft.submissions
FROM fruits ft
WHERE ft.fruit = 'Lemon'
) ft2
ON ft1.fruit_attribute = ft2.fruit_attribute
GROUP BY ft1.fruit;
CURRENT OUTPUT
| fruit | submissions | attributes_shared_lemon | attributes_not_shared_lemon |
|--------|-------------|-------------------------|-----------------------------|
| Lemon | 70 | 5 | 0 |
| Orange | 59 | 2 | 3 |