如何获得最大的日期记录并动态乘以

Posted

技术标签:

【中文标题】如何获得最大的日期记录并动态乘以【英文标题】: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 |
 +-----+-------------+ 

【问题讨论】:

【参考方案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

【讨论】:

以上是关于如何获得最大的日期记录并动态乘以的主要内容,如果未能解决你的问题,请参考以下文章

如何获得低于所选日期的最大值?

如何获得状态Powerbi中最后一个值的最大日期

如何设置子查询以获取具有最新日期和最大 ID 的单个记录?

您将如何使用 T-SQL 获得满足条件的顺序/连续记录的最大/最大计数

在运行 Sql 表最大日期逻辑时需要帮助

如何根据 MySQL 中的最大日期仅选择左表的一条记录?