我正在處理一個幾乎在我想要的地方的SQL查詢。我只想爲每個「attributes_share_lemon」和「attribites_not_shared_lemon」的平均提交添加兩列。如何在MySQL中添加平均值w/sum(case when ...)?
這裏是SQL小提琴,我是工作在這裏:
http://sqlfiddle.com/#!9/6ea5d8/8
這裏是創建和插入:
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);
我的查詢:
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 |
那麼,什麼是問題?哪裏不對?你的預期結果是什麼? –
第二句:我只想爲每個「attributes_share_lemon」和「attribites_not_shared_lemon」的平均提交添加兩列。 – lcm
也許會有點諷刺,但離侮辱還很遠。沒有什麼比「鹹」更強的詞。你不覺得我在幫忙嗎?即使你的問題很好,我會提供一些閱讀材料,可能會幫助你下一次準備更好的問題。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/和[**需要答覆?其實,不...你需要一個問題**](http://weblogs.sqlteam.com/jeffs/archive/2008/05/13/question-needed-not-answer.aspx) –