在表格中选择最小日期值

时间:2014-10-22 06:34:22

标签: sql oracle

我有这种格式的数据:

Account  security_name, broker_name balance_bf, tran_amt  tran_date

2323232  sec_a          br_a         400         -200      06-10-2014
2323232  sec_b          br_b         800         400       06-10-2014
2323232  sec_a          br_a         200         -300      06-10-2014
2323232  sec_a          br_a         200         -300      07-10-2014
2323232  sec_b          br_b         1200         400      09-10-2014

我需要编写一个结果集,使得Opening balance_bf基于security_name和Broker名称出现在每一行上。例如。

account  security_name   broker_name  balance_bf  tran_amt   tran_date   first_tran_date
2323232  sec_a          br_a         400         -200      06-10-2014  06-10-2014
2323232  sec_b          br_b         800         400       06-10-2014  06-10-2014
2323232  sec_a          br_a         400         -300      06-10-2014  06-10-2014
2323232  sec_a          br_a         400         -300      07-10-2014  06-10-2014
2323232  sec_b          br_b         800          400      09-10-2014  06-10-2014

Tran_date有一个时间戳,所以我可以订购它们我只想在每一行得到第一个balance_bf和第一个tran_date

我试过了

select account, security_name, broker_name,tran_amt, min(tran_date)first_tran_date
from customer_transactions group by account, security_name, broker_name,tran_amt order by tran_date;

当然这不起作用,因为金额会有所不同。请帮忙。

1 个答案:

答案 0 :(得分:3)

您可以使用FIRST_VALUE功能:

select Account, security_name, broker_name, balance_bf, tran_amt, tran_date,
   FIRST_VALUE(balance_bf) OVER (PARTITION BY security_name, broker_name ORDER BY tran_date) as first_balance,
   FIRST_VALUE(tran_date) OVER (PARTITION BY security_name, broker_name ORDER BY tran_date) as first_tran_date
from customer_transactions;