![](/img/trans.png)
[英]How to get least/min value from multiple columns but ignore 0 as min/least value using mysql?
[英]How to get min value from multiple columns for a row in SQL
我需要從4個(或更多)列中獲取第一個(分鍾)日期。
我試過了
從tbl中選擇min(col1,col2,col3)
這顯然是錯誤的。
假設我有這4欄
col1 | col2 | col3 | col4
1/1/17 | 2/2/17 | | 3/3/17
...在這種情況下,我要獲取的是col1(1/1/17)中的值。 是,這些列可以包含NULL。
我在dashDB中運行
列是日期數據類型,
該表中沒有ID或主鍵列,
我需要對查詢中的所有行執行此操作
列未按順序排列。 意味着col1不必在col2之前或必須為null,而col2不必在col3之前或必須為NULL ..依此類推
如果表中有一個id
列。 然后
詢問
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;
如果您的數據庫支持的功能最少,那是最好的方法
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
編輯:如果所有col為null,則可以將輸出硬編碼為null
。 下面的查詢應該工作。 我無法測試,但這應該可以。
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
如果您想初次約會,請使用coalesce()
:
select coalesce(col1, col2, col3, col4)
from t;
這將返回第一個非NULL
值(這是我解釋問題的一種方式)。 如果日期正確,則這將是最短日期。
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.