【问题标题】:Get the value from the first date and the last date sql从第一个日期和最后一个日期获取值sql
【发布时间】:2014-12-14 08:10:54
【问题描述】:

我有一个表格,在他们以这种格式进行的每笔交易后存储客户余额:

Client number    balance     tran_date
7734766688       23000       07-AUG-2014
7734766688       40000       07-AUG-2014
7734766688       20000       10-AUG-2014
7734766688       13000       15-AUG-2014
7734766688      400000       29-AUG-2014
7734766688      200000       02-SEP-2014

不,客户想要在 8 月 12 日至 8 月 31 日之间的声明,这意味着期初余额为 20000,截至 8 月 31 日的期末余额为 400000 我如何编写查询以获取截至查询的日期和最后的日期,因为可用的日期只是最后一笔交易?

我已经试过这个来获得期初余额,但似乎不够:

select balance from (select * from  client_balances where client_number = '7734766688' 
order by TRAN_DATE asc) 
where TRAN_DATE >= '01-AUG-2014' and rownum =1;

请帮忙,我卡住了。

【问题讨论】:

  • 您提供的数据中的DATE_LAST_TXN 列是什么?
  • 抱歉,这是 tran_date
  • client_Balances 表是否有 id 列?
  • 很遗憾没有。 Tbale 没有 ID 列
  • 当客户想要 2014 年 8 月 7 日至 2014 年 8 月 17 日之间的报表时,期初余额是多少? 63000 ?

标签: sql oracle10g


【解决方案1】:
with client_balances as (
select '7734766688' client_number, 23000 balance, to_date('07-08-2014', 'DD-MM-YYYY') tran_date from dual
union all select '7734766688', 40000, to_date('07-08-2014', 'DD-MM-YYYY') from dual
union all select '7734766688', 20000, to_date('10-08-2014', 'DD-MM-YYYY') from dual
union all select '7734766688', 13000, to_date('15-08-2014', 'DD-MM-YYYY') from dual
union all select '7734766688', 400000, to_date('29-08-2014', 'DD-MM-YYYY') from dual
union all select '7734766688', 200000, to_date('02-09-2014', 'DD-MM-YYYY') from dual
),
client_balances_analytic as (
select client_number, balance, tran_date, 
       lag(balance) over(partition by client_number order by tran_date) prev_balance,
       lag(tran_date) over(partition by client_number order by tran_date) prev_tran_date
from client_balances)
select tran_date_start, balance_start, tran_date_end, balance_end from (
  select case when tran_date = to_date('12-08-2014', 'DD-MM-YYYY') then tran_date else nvl(prev_tran_date, tran_date) end tran_date_start, 
         case when tran_date = to_date('12-08-2014', 'DD-MM-YYYY') then balance else nvl(prev_balance, balance) end balance_start, 
         row_number() over(order by tran_date) rw,
         last_value(tran_date) over(order by tran_date rows between current row and unbounded following) tran_date_end,
         last_value(balance) over(order by tran_date rows between current row and unbounded following) balance_end
   from client_balances_analytic 
  where client_number = '7734766688' and tran_date between to_date('12-08-2014', 'DD-MM-YYYY') and to_date('31-08-2014', 'DD-MM-YYYY')
) where rw = 1;

lag 函数从上一行检索数据

此查询可能不适用于关系(相同的 tran_dates)。在这种情况下,您需要一些额外的标准来对交易进行排序(以便获得最早的)

【讨论】:

    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2016-01-07
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    相关资源
    最近更新 更多