【问题标题】:How to get greatest Date record and multiply to that dynamically如何获得最大的日期记录并动态乘以
【发布时间】:2021-03-17 21:09:28
【问题描述】:

大家好,我想获得最大的日期记录并动态乘以下面是我的表的示例结构,这里是 DB fiddle https://dbfiddle.uk/?rdbms=oracle_18&fiddle=cde3fdc07915a2e8c23195be646c5a20

+-----+-------------+-----------+--------+----------------+
| ID  | Sequence Id |   Date    | Amount |   Frequency    |
+-----+-------------+-----------+--------+----------------+
| 123 |           1 | 01-Jan-20 |     50 | Monthly        |
| 123 |           2 | 01-Feb-20 |     50 | Monthly        |
| 123 |           3 | 01-Mar-20 |    150 | Monthly        |
| 123 |           4 | 01-Apr-20 |    200 | Monthly        |
| 123 |           5 | 01-May-20 |    510 | Monthly        |
| 123 |           1 | 01-Jan-20 |    510 | Quarterly      |
| 123 |           2 | 01-Apr-20 |    300 | Quarterly      |
| 123 |           1 | 01-Jan-20 |    600 | Semi-Annually  |
+-----+-------------+-----------+--------+----------------+

我想在过滤器的帮助下动态检索数据,并想根据频率乘以数量。 根据日期获取最大记录,如果频率为每月,则乘以 12,如果频率为季度,则乘以 4,如果频率为半年,则乘以 2

Ex. 1. If we run query select ID, Rent from Table where Date is greater than or equal 01-jan-2020 and less than or equal to 01-may-2020 and frequency equal to Monthly then out put should be like below -
 +-----+-------------+
 | ID  |        Rent |
 +-----+-------------+
 | 123 |       6,120 |
 +-----+-------------+ 

2. If we run query select ID,Rent from Table where Date is greater than or equal 01-jan-2020 and less than or equal to 01-may-2020 and frequency equal to Quarterly then out put should be like below -
 +-----+-------------+
 | ID  |        Rent |
 +-----+-------------+
 | 123 |        1200 |
 +-----+-------------+ 
3. If we run query select ID,Rent from Table where Date is greater than or equal 01-jan-2020 and less than or equal to 01-may-2020 and frequency equal to Semi-Annually then out put should be like below -
 +-----+-------------+
 | ID  |        Rent |
 +-----+-------------+
 | 123 |        1200 |
 +-----+-------------+ 

【问题讨论】:

    标签: sql oracle datetime case greatest-n-per-group


    【解决方案1】:

    如果你想同时处理多个 id 和频率,那么你可以像这样使用row_number()

    select id,
        amount * case frequency
            when 'Monthly'       then 12
            when 'Quaterly'      then 4
            when 'Semi-Annually' then 2
        end as rent
    from (
        select t.*, row_number() over(partition by id, frequency order by StartDate desc) rn
        from table1 t
        where StartDate between date '2020-01-01' and date '2020-05-01' and frequency = 'Monthly'
    ) t
    where rn = 1
    

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 2012-05-16
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多