MySQL:从一列

时间:2016-10-31 08:25:36

标签: mysql

假设我有这张表:

mytable的

+------+-------+
| type | count |
+------+-------+
| red  | 4     |
| blue | 3     |
| red  | 2     |
| blue | 7     |
+------+-------+

现在我想要回来:

+--------+---------+
| maxRed | maxBlue |
+--------+---------+
| 4      | 7       |
+--------+---------+

我该怎么做?

这就是我试过的

SELECT MAX(count) as maxRed, 0 as maxBlue FROM mytable WHERE type='red'

UNION

SELECT 0 as maxRed, MAX(count) as maxBlue FROM mytable WHERE type='blue'

但它不起作用,只有结果

+--------+---------+
| maxRed | maxBlue |
+--------+---------+
| 4      | 0       |
| 0      | 7       |
+--------+---------+

4 个答案:

答案 0 :(得分:7)

为了使您的查询起作用,您只需要用另一个查询包装它:

SELECT MAX(maxRed) as maxRed, MAX(maxBlue) as maxBlue
FROM(
    SELECT MAX(count) as maxRed, 0 as maxBlue FROM mytable WHERE type='red'
    UNION
    SELECT 0 as maxRed, MAX(count) as maxBlue FROM mytable WHERE type='blue') t

更优雅的方式是条件聚合:

SELECT MAX(CASE WHEN t.type = 'red' THEN t.count END) as maxRed,
       MAX(CASE WHEN t.type = 'blue' THEN t.count END) as maxBlue
FROM mytable t
WHERE t.type IN('blue','red')

答案 1 :(得分:2)

这是怎么做的:

SELECT
MAX(CASE WHEN type = 'red' THEN `count` ELSE NULL END) AS maxRed,
MAX(CASE WHEN type = 'blue' THEN `count` ELSE NULL END) AS maxBlue
FROM
mytable
WHERE type IN ('red', 'blue');

答案 2 :(得分:1)

SELECT type,MAX(count) FROM mytable group by type 

这将返回垂直而非水平的type和maxcount,并且可以对n个记录进行缩放。

如果水平数据无关紧要,否则您可以使用上面建议的用例答案,但是对于每个不同的数据值,都需要这样的情况。

答案 3 :(得分:-1)

<强> 修改 由于下面的评论我在真实数据上测试过,当mytable被索引时,我的版本对于大表来说要快一点。对于那些争论它的人,请测试自己并报告回来。

 select 
(select max(count) from mytable  WHERE type='red') aa,
(select max(count) from mytable  WHERE type='blue') bb