mysql - 如何从表中获取最低值

标签 mysql sql database

问题一

如何从表中获取 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

最佳答案

没有 union 你可以简单地合并 leastmin功能:

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
  • least 的对立函数是greatest
  • min 的反函数是max ;-)

适用于 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

关于mysql - 如何从表中获取最低值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50876464/

相关文章:

mysql - 更新并显示 mysql 查询

mysql - 在 MySQL 中将列名作为参数传递

mysql - 没有多行的 SQL 连接

mysql - 我的触发语句有问题吗?

MySQL 问题。无法将 select 生成的文件定位到输出文件 '/tmp/aa.txt'

sql - 如何在 BigQuery Standard SQL 中进行可重复采样?

sql - 如何计算运行平均值

java - 数据库 INSERT 未向表添加数据

mysql - SQL 连接并获取另一列

sql - 如何判断触发器代码是否正在复制订阅服务器上执行?