我附上一张图片作为我的样本数据,我想要做的是获取trans_date的最大月份和年份,并获得其flow_amt的总和。
示例输出
AF935906 | 22335.86 | DEC-17
这是我的上一次查询,但输出错误
select ltd.acid, sum(ltd.flow_amt) sum_flow_amt, MAX(to_char(ltd.tran_date, 'Mon-YYYY')) as transac_date
from tbaadm.ltd ltd
where
ltd.tran_date <= '31-DEC-17' and ltd.acid = 'AF935906'
由于
答案 0 :(得分:4)
您正在将MAX
应用于字符串(TO_CHAR(...)
。因此,比较是字母的,'Jan-2001'大于'Dec-2017',因为'D'出现在'J'之前字母表。
因此请在日期使用MAX
,然后才应用格式函数TO_CHAR
。
select
ltd.acid,
sum(ltd.flow_amt) as sum_flow_amt,
to_char(max(ltd.tran_date), 'Mon-YYYY') as transac_date
from tbaadm.ltd ltd
where ltd.tran_date <= date '2017-12-31' and ltd.acid = 'AF935906'
group by ltd.acid;
更新:您说您只想要上个月的总和。因此,将Oracle的KEEP LAST
子句添加到SUM
。
select
ltd.acid,
sum(ltd.flow_amt) keep (dense_rank last order by trunc(tran_date, 'month')) as sum_flow_amt,
to_char(max(ltd.tran_date), 'Mon-YYYY') as transac_date
from tbaadm.ltd ltd
where ltd.tran_date <= date '2017-12-31' and ltd.acid = 'AF935906'
group by ltd.acid;
答案 1 :(得分:1)
我想你想要更像这样的东西:
select acid, yyyymm, sum_flow_amt
from (select ltd.acid, to_char(ltd.tran_date, 'YYYY-MM') as yyyymm,
max(tran_date) as max_tran_date,
sum(ltd.flow_amt) as sum_flow_amt,
row_number() over (partition by ltd.acid order by to_char(ltd.tran_date, 'YYYY-MM') desc) as seqnum
from tbaadm.ltd ltd
where ltd.tran_date <= date '2017-12-31' and ltd.acid = 'AF935906'
group by ltd.acid, to_char(ltd.tran_date, 'YYYY-MM')
) ad
where seqnum = 1;
我更喜欢以YYYY-MM格式输出。如果您真的想要其他格式的日期,请使用:
select acid, to_char(max_tran_date, 'MMM-YYYY') as mmmyyyy, sum_flow_amt