MySQL - 找到" Max"多列中10条记录的绝对值?

时间:2016-09-16 15:10:24

标签: mysql sql max

我有一张看起来像这样的表:

 Country | Item | Col1 | Col2 | Col3 | Col4
 4       | 4    | .152 | .01  | .65  | 1 
 9       | 6    | .145 | .98  | .469 | .001
 56      | 7    | .001 | .987 | .011 | .223
 78      | 2    | -18  | .269 | -.70 | .1

等等。我想从Col1Col2Col3Col4中找到前10个最大ABS(条目)。所以在这种情况下,答案是:

-18
1 
.987
.98
-.70
.65
.469
.223 
.... 

等等。但是我该怎么做呢?我遇到了两个this,它详细说明了如何根据 coumn找到最大绝对值n列,还有this,但只找到行的最大值每个行。我该如何将两者结合起来?

修改

正如答案所示,我尝试过这样的事情:

SELECT MAX(ABS(`Col1`)) as `absValue` FROM Table1
UNION ALL 
SELECT MAX(ABS(`Col2`)) as `absValue` FROM Table1 
UNION ALL 
SELECT MAX(ABS(`Col3`)) as `absValue` FROM Table1
UNION ALL 
SELECT MAX(ABS(`Col4`)) as `absValue` FROM Table1
ORDER BY `absValue` DESC
LIMIT 10 

但得到了:

18
1
0.9869999885559082
0.699999988079071

我做错了什么? SQL Fiddle

非常感谢任何帮助,谢谢!!

3 个答案:

答案 0 :(得分:2)

 SELECT  `value` 
 FROM (
           SELECT col1 as `value`  FROM yourTable
           UNION all
           SELECT col2 as `value`  FROM yourTable
           UNION all
           SELECT col3 as `value`  FROM yourTable
           UNION all
           SELECT col4 as `value`  FROM yourTable
      ) T
ORDER BY `value` DESC
LIMIT 10

正如大卫和卡米尔所说,你不需要子查询

<强> SQL DEMO

SELECT col1 as `value`  FROM Table1
UNION all
SELECT col2 as `value`  FROM Table1
UNION all
SELECT col3 as `value`  FROM Table1
UNION all
SELECT col4 as `value`  FROM Table1
ORDER BY `value` DESC
LIMIT 10

QUESTION EDIT 之后尝试

SELECT ABS(`Col1`) as `absValue` FROM Table1
UNION ALL 
SELECT ABS(`Col2`) as `absValue` FROM Table1 
UNION ALL 
SELECT ABS(`Col3`) as `absValue` FROM Table1
UNION ALL 
SELECT ABS(`Col4`) as `absValue` FROM Table1
ORDER BY `absValue` DESC
LIMIT 10 

OR以获得确切的输出

SELECT `Col1` as `value` FROM Table1
UNION ALL 
SELECT `Col2` as `value` FROM Table1 
UNION ALL 
SELECT `Col3` as `value` FROM Table1
UNION ALL 
SELECT `Col4` as `value` FROM Table1
ORDER BY ABS(`value`) DESC
LIMIT 10 

答案 1 :(得分:1)

为每个列获取10个最大值并从所有列中检索10个最高值:

select max_value
from (
  (select col1 AS max_value
  from yourtable
  order by col1 desc
  limit 10)
  union all
  (select col2
  from yourtable
  order by col2 desc
  limit 10)
  union all
  (select col3
  from yourtable
  order by col3 desc
  limit 10)
  union all
  (select col4
  from yourtable
  order by col4 desc
  limit 10)
  ) foo
order by max_value desc
limit 10

答案 2 :(得分:1)

select * from ( 
select Col1 as data from database1 
UNION 
select Col2 as data from database1 
UNION 
select Col3 as data from database1 
UNION 
select Col4 as data from database1 
) as T order by data desc ;

union命令在这个场景中非常有用