用 SQL 从多行数据里选出最大值或最小值很容易——通过 GROUP BY子句对合适的列进行聚合操作,并使用 MAX 或 MIN 聚合函数就可以求出。那么,从多列数据里选出最大值该怎么做呢?
目录
1、建表SQL
2、查询SQL
(1)方法一
(2)方法二
3、查询结果
1、建表SQL
DROP TABLE IF EXISTS `greatests`;
CREATE TABLE `greatests` (
`key` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
`x` int(255) NULL DEFAULT NULL,
`y` int(255) NULL DEFAULT NULL,
`z` int(255) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of greatests
-- ----------------------------
INSERT INTO `greatests` VALUES ('A', 1, 2, 3);
INSERT INTO `greatests` VALUES ('B', 6, 5, 2);
INSERT INTO `greatests` VALUES ('C', 4, 7, 1);
INSERT INTO `greatests` VALUES ('D', 3, 3, 8);
2、查询SQL
(1)方法一
首先求出了 x 和 y 中的较大值,接下来需要拿这个较大值和 z 进行比较。
SELECT `key`,
CASE WHEN CASE WHEN x < y THEN y ELSE x END < z
THEN z
ELSE CASE WHEN x < y THEN y ELSE x END
END AS greatest
FROM greatests;
(2)方法二
先进行行列转换,然后使用 MAX 函数来求解。
SELECT `key`, MAX(col) AS greatest
FROM (SELECT `key`, x AS col FROM greatests
UNION ALL
SELECT `key`, y AS col FROM greatests
UNION ALL
SELECT `key`, z AS col FROM greatests)TMP
GROUP BY `key`;