首页 > 解决方案 > 如何从表中获取最低值

问题描述

问题 1

对于 ID_CAR,如何从表中获取最低值(非空)?例如,ID_CAR 1 的最小值是 50,ID_CAR 2 的最小值是 50,ID_CAR 3 的最小值是 300。我不需要重复,我只需要一个值用于一辆车。

ID_CAR | col_1 | col_2 | col_3 | col_4 | col_5 | col_6 

1      | null  | 250   | 300   | null  | 900   | null
2      | 100   | null  | 300   | 600   | 200   | 100
1      | 300   | 100   | 800   | 100   | 50    | 900
3      | 300   | 4000  | null  | null  | null  | null
2      | null  | null  | null  | 50    | null  | 100
4      | 400   | 900   | 500   | 700   | 800   | 500

问题 2 在此示例中,col_* 中的值是天。我需要在 col_date 中添加天数并达到最低值。例如,ID_CAR 1 的最低日期是 2018-01-03 (col_2),ID_CAR 2 的最低日期是 2018-01-15 (col_4)。

ID_CAR | col_1 | col_2 | col_3 | col_4 | col_5 | col_6 | col_date

1      | null  | 2     | 3     | null  | 5     | null  | 2018-01-01
2      | 1     | null  | 3     | 6     | 10    | 10    | 2018-01-13
1      | 3     | 20    | 80    | 10    | 50    | 90    | 2018-01-02
3      | 30    | 40    | null  | null  | null  | null  | 2018-01-03
2      | null  | null  | null  | 5     | null  | 10    | 2018-01-10
4      | 10    | 9     | 5     | 70    | 8     | 50    | 2018-01-07

标签: mysqlsqldatabase

解决方案


没有union你可以简单地结合最小最小功能:

select
  ID_CAR,min(least(col_1,col_2,col_3,col_4,col_5,col_6)) lowest_value
from
  table
group by
  ID_CAR

或者如果你有你需要或功能的null价值观ifnullcoalesce

select
  ID_CAR,
  min(least(
    ifnull(col_1,~0),
    ifnull(col_2,~0),
    ifnull(col_3,~0),
    ifnull(col_4,~0),
    ifnull(col_5,~0),
    ifnull(col_6,~0)
  )) as lowest_value
from
  table
group by
  ID_CAR
  • ~0是 mysql 中的最大 bigint
  • 的反函数leastgreatest
  • 的相反功能minmax;-)

适用于 Mysql、Oracle、Postgres、Hive ...

问题 2,类似这样:

select
  ID_CAR,
  min(least(
    DATE_ADD(col_date, INTERVAL ifnull(col_1,0) DAY),
    DATE_ADD(col_date, INTERVAL ifnull(col_2,0) DAY),
    DATE_ADD(col_date, INTERVAL ifnull(col_3,0) DAY),
    DATE_ADD(col_date, INTERVAL ifnull(col_4,0) DAY),
    DATE_ADD(col_date, INTERVAL ifnull(col_5,0) DAY),
    DATE_ADD(col_date, INTERVAL ifnull(col_6,0) DAY)
  )) as lowest_date
from
  table
group by
  ID_CAR

或像这样(除非所有列都可以为空):

select
  ID_CAR,
  DATE_ADD(col_date, INTERVAL min(least(
    ifnull(col_1,~0),
    ifnull(col_2,~0),
    ifnull(col_3,~0),
    ifnull(col_4,~0),
    ifnull(col_5,~0),
    ifnull(col_6,~0)
  )) DAY) as lowest_date
from
  table
group by
  ID_CAR

推荐阅读