MySQL SUM在同一个表上有多个GROUP BY
作者:互联网
在MySQL的同一个表中,基于不同组的条件生成多个和结果的最佳方法是什么?
我相信我选择不好,但我无法找到更好的方法.
想象一下,我有一个订单表,我跟踪订单的客户,它的价值和订单的一些限定符(类型).我想对按订单类型组合分组的给定客户的总订单求和:
delimiter $$
CREATE TABLE `orders` (
`idorder` int(11) NOT NULL,
`value` double DEFAULT NULL,
`idclient` int(11) DEFAULT NULL,
`type1` int(11) DEFAULT NULL,
`type2` int(11) DEFAULT NULL,
`type3` bit(1) DEFAULT NULL,
PRIMARY KEY (`idorder`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
我的选择:
SELECT T0.idclient, T1.condition1, T2.condition2, T3.condition3 FROM
(SELECT 1 AS idclient) AS T0
LEFT JOIN
(SELECT idclient, SUM(value) condition1 FROM `test`.`orders` WHERE idclient = 1 AND type1 = 1 AND type2 = 1 AND type3 = 0) AS T1
ON T0.idclient = T1.idclient
LEFT JOIN
(SELECT idclient, SUM(value) condition2 FROM `test`.`orders` WHERE idclient = 1 AND type1 = 1 AND type2 = 1 AND type3 = 1) AS T2
ON T0.idclient = T2.idclient
LEFT JOIN
(SELECT idclient, SUM(value) condition3 FROM `test`.`orders` WHERE idclient = 1 AND type1 = 1 AND type2 = 0 AND type3 = 0) AS T3
ON T0.idclient = T3.idclient;
我错过了什么吗?
输出:
+----------+------------+------------+------------+
| idclient | condition1 | condition2 | condition3 |
+----------+------------+------------+------------+
| 1 | 10 | 20 | 30 |
+----------+------------+------------+------------+
1 row in set (0.00 sec)
数据:
INSERT INTO `orders` VALUES (1,5,1,1,1,'\0'),(2,5,1,1,1,'\0'),(3,20,1,1,1,''),(4,5,1,1,0,'\0'),(5,25,1,1,0,'\0');
解决方法:
我更像是一个SQL Server的人,但这是一个让你有动力的刺激.您可以使用CASE表达式来帮助某些订单类型的SUM()订单.
例如:
SELECT
idclient AS [Client ID]
,COUNT(value) AS [Total Orders]
,SUM(value) AS [Total Order Value]
,SUM( CASE WHEN type1 = 'some type' THEN value ELSE 0 END) AS [Order Combo 1]
,SUM( CASE WHEN type1 = 'some type' AND type2 = 'another type' THEN value ELSE 0 END) [Order Combo 2]
,SUM( CASE WHEN type1 = 'some type' AND type2 = 'another type' AND type3 = 'another type' THEN value ELSE 0 END) [Order Combo 3]
FROM 'test'.'orders'
GROUP BY idclient
这将对[idclient]上的订单进行分组,并将SUM([value])分配给某些订单记录满足以下条件或您指定的组合的实例.
因此,如果客户有一个订单,其中[type1]是Apples而[type2]是Oranges,则可以在名为[Apple / Orange Orders]之类的新列下的SUM([value])为1.
结果还可以包括多个字段/列中相同记录的其他组合.如果这是一个问题,只需将CASE移动到GROUP BY,将每个组合分解为结果集中的单独记录.
希望这可以帮助!
标签:query-performance,mysql 来源: https://codeday.me/bug/20190806/1596945.html