mysql - 如何从表中获取最低值
问题描述
问题 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
解决方案
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
价值观ifnull
coalesce
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
推荐阅读
- go - 如何通过循环列表创建多个 CRON 函数
- objectbox - ObjectBox 关系 - 想要返回仅包含关系框的列表
- http - 为什么我得到一个 200 状态码,然后又被重定向回登录页面?
- java - 如何通过Java反射从父类中获取嵌套类
- python - Dieharder 随机测试套件 - 令人怀疑的好结果
- c# - 如何使用计时器每 x 秒更改一次标签文本
- swiftui - Xcode 11 beta 4 - 不推荐使用 relativeWidth
- java - 如何在heroku中使用nodejs使jar文件可执行
- python - 对象检测torchvision:IOError:[Errno 2]没有这样的文件或目录:
- excel - 通过vba在excel中插入公式的问题