返回总和而不是像SQL查询那样的数据透视表中的值?

时间:2015-10-12 23:57:18

标签: mysql sql

我有一个很好的小查询,除了一点点之外,几乎可以满足我的需求。而不是返回列下的值" Orange"和"柠檬"我需要知道该属性和水果的提交数量。

这是我的表和一些测试数据:

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
  fruit_attribute, submissions,
  MAX(IF(t1.fruit = 'Orange', t1.fruit_attribute, NULL)) AS Orange,
  MAX(IF(t1.fruit = 'Lemon', t1.fruit_attribute, NULL)) AS Lemon
FROM fruits t1
GROUP BY
  fruit_attribute;

Here is a sqlfiddle page for a demo

非常感谢所有帮助!

2 个答案:

答案 0 :(得分:5)

我想你要总结#ifdef列:

submissions

我更喜欢将SELECT fruit_attribute, SUM(CASE WHEN t1.fruit = 'Orange' THEN t1.submissions ELSE 0 END) AS Orange, SUM(CASE WHEN t1.fruit = 'Lemon' THEN t1.submissions ELSE 0 END) AS Lemon FROM fruits t1 GROUP BY fruit_attribute; 用于CASE,因为IF()是几乎所有数据库都可用的标准版。

答案 1 :(得分:1)

如果你想知道提交的数量,那么使用sum()和if()而不是max():

SUM(IF(t1.fruit = 'Orange', submissions, 0)) AS Orange