2017-05-09 230 views
-1

我正在研究SQL DB2,我想檢索一次具有最大日期值的字段,但日期是三列(日,月,年)。SQL:DB2 3列(日,月,年)日期的最大值和最小值

你能幫我嗎?

非常感謝。

+0

你嘗試過什麼?您可以連接列以形成日期 – uSeruSher

+0

將列組合爲字符串然後日期然後在組合列上使用max:http://stackoverflow.com/questions/4852139/converting-a-string-to-a-date -in-db2 – xQbert

+0

SELECT YEAR,MONTH,DAY FROM FILE WHERE YEAR =(從文件中選擇MAX(YEAR))==>但是這隻會返回最大年份的日期。我想檢索最大日期。我不知道如何連接,因爲它的數字字段可以請給我更多的解釋 – Fazah

回答

0

試試這個代碼,請:

select distinct year, month, day 
from (
    select year, month, day, rank() over(order by year desc, month desc, day desc) as rn 
    from [your table name] 
) t 
where rn = 1 

UPDATE1: 如果你有合同編號一些領域,那麼你就需要通過聲明在使用分區()

select distinct contract_number, year, month, day 
from (
    select contract_number, year, month, day, rank() over(partition by contract_number order by year desc, month desc, day desc) as rn 
    from [your table name] 
) t 
where rn = 1 
+0

它的工作原理,但我試圖從其他文件一起檢索其他文件也當我添加其他列它不工作 – Fazah

+0

Fazah,你嘗試從其他表添加列?這個結構是如何看起來的? –

+0

其實我使用很多表格,我需要檢索有很多條件的字段,其中一個是最大日期,另一個是最小日期等... – Fazah

0

你可以做下面的事情。但是您需要使用日期,月份,年份格式的格式更改下面的查詢。

select * from urtable where to_date(year||'-'||month||'-'||day,'yyyy-mon-dd') in 
(select max(to_date(year||'-'||month||'-'||day,'yyyy-mon-dd'))) from urtable) 
0
select * from yourtable 
order by colyear desc, colmonth desc, colday desc 
fetch first rwos only 
+0

我覺得我並不清楚自己在展示問題的方式,我會舉一個例子:我的表中有很多合約C1有這樣的日期:日:01月:02年:2017和C1有另一個這樣的日期:日:01月:01年:2017年和其他像這樣的合同。我需要做的是取回合同:C1與本合同的最大日期,即日:01月:02年:2017年和相同或其他對照,所以我將有C1的最大日期和C2與其最大日期等等。我希望我現在更清楚,並且很多幫助。 - – Fazah

相關問題