plsql查询在conditon和不同月份之间进行计数

时间:2015-05-22 12:45:08

标签: sql oracle

我需要编写一个查询来计算最后3个月,6,9,12个月之间进行的交易,金额应该介于100 - 500然后501 - 1000然后是1001到2000之间。 简单有效的写作方式。

3个月

Select Count(Transactionid),
       Customerid 
From TransactionTable where
 Transactiondate Between To_Char(Add_Months(Sysdate ,-3), 'dd-MON-yy') 
And To_Char(Sysdate, 'dd-MON-yy' ) 
and transaction_value between 100 and 500
 GROUP BY Customerid  

通过这种方式,我想要多次最简单的方式

2 个答案:

答案 0 :(得分:0)

这应该处理你描述的逻辑。我已经将每组变量声明为一个数组,然后可以为结果循环。

declare
    type mth_nbr is table of number;
    type range_start is table of number;
    type range_end is table of number;
    l_mth_nbr mth_nbr := mth_nbr(3,6,9,12);
    l_range_start range_start := range_start(100,501,1001,2001);
    l_range_end range_end := range_end(500,1000,2000,3000);
    l_cnt number := l_mth_nbr.count;
begin
    for i in 1..l_cnt
    loop
        select count(transactionid),
                    customerid 
        from transactiontable
        where transactiondate between to_char(Add_Months(Sysdate, -l_mth_nbr(i)),'dd-MON-yy') and to_char(sysdate, 'dd-MON-yy')
        and transaction_value between l_range_start(i) and l_range_end(i)
        group by customerid;
    end loop;
end;

答案 1 :(得分:0)

希望您并不是真的将交易日期存储为字符,而是存储日期。

在这种情况下,您应该使用以下逻辑:

transaction date between date1 and date1

......不......

transaction date between string1 and string2

所以:

transactiondate between Add_Months(Sysdate, -l_mth_nbr(i)) and sysdate