2017-05-29 70 views
0

我需要從同一個表內的兩個不同列中返回兩個最大日期。我想要結果在同一行。 這是我的表中的數據:計算最大日期

If i have this   
store item tran-code date 
1788 2004635 1  17.05.27 
1788 2004635 2  17.05.27 
1788 2004635 30  17.05.26 
1788 2004635 2  17.05.21 
1788 2004635 1  17.05.21 
1788 2004635 2  17.05.20 
1788 2004635 1  17.05.20 

,我想這...

store item tran-code date 
1788 2004635 1  17.05.27 
1788 2004635 30  17.05.26 

,但如果你可以讓我回到這一點,這將是完美的

store item  date_1 date_30 
1788 2004635 17.05.27 17.05.26 

其中DATE_1是tran-code的最大日期= 1和 date_30是tran-code的最大日期= 30

+2

你使用的是什麼RDBMS和版本? – Lamak

+0

使用SQL Developer –

+2

但你使用的是什麼數據庫引擎?,Oracle,SQL Server,Postgresql,mysql ...? – Lamak

回答

1

你可以使用

select a.store, a.item, max(a.date) as date_1, t.date_30 
from my_table a 
inner join (
select store, item, max(date) as date_30 
from my_table a 
where a.trans-code = 30 
group by store, item 
) t on a.store = t.store and a.item = t.item 
group by a.store, a.item, t.date_30 
+0

我試過這個,並給出了錯誤ORA-00937:「不是一個單一組的功能」。第1行8.不知道我在做什麼錯... –

+0

在主要選擇缺少組..回答更新.. – scaisEdge

+0

仍然錯誤,ORA-00979:「不是GROUP BY表達式」在第1行52.第52列匹配t.date_30 –

1

如果你只選擇1套,如果商店和項目,然後就可以用這個。但是,如果您添加更多商店和商品,請使用@ scaisEdge的答案進行加入。

select distinct store,item, 
(select max(date) from table1 where tran-code=1) as date_1 
,(select max(date) from table1 where tran-code=30) as date_30 
from table1; 
+0

我'已經嘗試過你的消化和返回錯誤:ORA-00923: 00923. 00000 - 「FROM關鍵字沒有找到預期的地方」 –

+0

它給第一個錯誤選擇最大(日期) –

+0

我把從子句之後,因此錯誤。更新。現在檢查 – Utsav

1
SELECT STORE,item ,tran_code,date1 FROM (
SELECT a.*,Row_Number() OVER (PARTITION BY tran_code ORDER BY date1 DESC) rnk FROM tran a) 
WHERE tran_code IN (1,30) AND rnk=1 
;