[英]How to get min value from multiple columns for a row in SQL
I need to get to first (min) date from a set of 4 (or more) columns. 我需要从4个(或更多)列中获取第一个(分钟)日期。
I tried 我试过了
select min (col1, col2, col3) from tbl 从tbl中选择min(col1,col2,col3)
which is obviouslly wrong. 这显然是错误的。
let's say I have these 4 columns 假设我有这4栏
col1 | col2 | col3 | col4
1/1/17 | 2/2/17 | | 3/3/17
... in this case what I want to get is the value in col1 (1/1/17). ...在这种情况下,我要获取的是col1(1/1/17)中的值。 and Yes, these columns can include NULLs. 是,这些列可以包含NULL。
I am running this in dashDB 我在dashDB中运行
the columns are Date data type, 列是日期数据类型,
there is no ID nor Primary key column in this table, 该表中没有ID或主键列,
and I need to do this for ALL rows in my query, 我需要对查询中的所有行执行此操作
the columns are NOT in order. 列未按顺序排列。 meaning that col1 does NOT have to be before col2 or it has to be null AND col2 does NOT have to be before col3 or it has to be NULL .. and so on 意味着col1不必在col2之前或必须为null,而col2不必在col3之前或必须为NULL ..依此类推
If a id
column in your table. 如果表中有一个id
列。 Then 然后
Query 询问
select t.id, min(t.col) as min_col_value from(
select id, col1 as col from your_table
union all
select id, col2 as col from your_table
union all
select id, col3 as col from your_table
union all
select id, col4 as col from your_table
)t
group by t.id;
If your DB support least function, it is the best approach 如果您的数据库支持的功能最少,那是最好的方法
select
least
(
nvl(col1,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col2,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col3,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col4,TO_DATE('2901-01-01','YYYY-MM-DD'))
)
from tbl
Edit: If all col(s) are null, then you can hardcode the output as null
. 编辑:如果所有col为null,则可以将输出硬编码为null
。 The below query should work. 下面的查询应该工作。 I couldn't test it but this should work. 我无法测试,但这应该可以。
select
case when
least
(
nvl(col1,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col2,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col3,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col4,TO_DATE('2901-01-01','YYYY-MM-DD'))
)
= TO_DATE('2901-01-01','YYYY-MM-DD')
then null
else
least
(
nvl(col1,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col2,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col3,TO_DATE('2901-01-01','YYYY-MM-DD')),
nvl(col4,TO_DATE('2901-01-01','YYYY-MM-DD'))
)
end
as min_date
from tbl
If you want the first date, then use coalesce()
: 如果您想初次约会,请使用coalesce()
:
select coalesce(col1, col2, col3, col4)
from t;
This returns the first non- NULL
value (which is one way that I interpret the question). 这将返回第一个非NULL
值(这是我解释问题的一种方式)。 This will be the minimum date, if the dates are in order. 如果日期正确,则这将是最短日期。
Select Id, CaseWhen (Col1 <= Col2 OR Col2 is null) And (Col1 <= Col3 OR Col3 is null) Then Col1 When (Col2 <= Col1 OR Col1 is null) And (Col2 <= Col3 OR Col3 is null) Then Col2 Else Col3 End As Min From YourTable
这适用于3列,用相同的方式可以编写4列或更多列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.