【问题标题】:SELECT records FROM amount_history WHERE amount1 is l<= max amount2 in last 3 yearsSELECT records FROM amount_history WHERE amount1 is l<= max amount2 in last 3 years
【发布时间】:2017-05-21 15:57:54
【问题描述】:

我知道基本的 SQL,但我正在尝试提出一个超出我能力范围的查询。

AMOUNT_HISTORY 表是这样的

我可以为生效日期添加一个输入参数,比如有效日期。

过去 3 年 RefNo 1 的最高 Amount1 是 12,000,这是

RefNo 2 在过去 3 年的最高 Amount1 为 22,000,大于 Amount2 在生效日期 - 在这种情况下我需要选择 RefNo。

请注意日期可以追溯到更远,因此需要最后 3 个日期标准。只有有效日期的周年纪念日才会有日期。通常我会添加我迄今为止开发的查询,但我没有比简单的 Select From Where 更进一步,所以没有太大进展。任何帮助表示赞赏。

【问题讨论】:

  • 期望的输出是什么?只要过去 3 年的最大 Amount1 大于生效日期的 Amount2,就只是 RefNo?或有关 RefNo 的更多信息? (也许该 RefNo 的所有三行,从生效日期起三年前?)另外,三年前也应该包括 2014 年,还是不包括?
  • 只要过去 3 年的最大金额 1 大于生效日期的金额 2,所需的输出为 refno, amount2。自 2017 年 1 月 1 日起生效 3 年后应包括 2017 年、2016 年和 2015 年。谢谢

标签: sql oracle


【解决方案1】:

首先,您只需选择日期在“生效日期减去两年”和“生效日期”之间的行。这在WHERE 子句中做得最好,带有between 条件,使用add_months() 从生效日期减去两年。注意 - 我使用 dt 作为列名(date 在 Oracle 中保留,不应用作标识符);我将生效日期作为绑定变量传递。

然后,从剩余的行中,按refno 分组,并将max(amount1) 与生效日期的amount2 进行比较。这是组级别的比较,而不是单个行级别的比较,所以它放在 HAVING 子句中,而不是在 WHERE 子句中。

最后,生效日期的amount2 是在行级别,而不是在组级别;所以我们需要一个小技巧。我使用“条件最大值” - max() 函数应用于表达式 amount2 当日期是生效日期时,但 null 在其他日期。 case 表达式非常适合。

with
     test_data ( refno, dt, amount1, amount2 ) as (
       select 1, date '2017-01-01', 12000, 12000 from dual union all
       select 1, date '2016-01-01', 11000, null  from dual union all
       select 1, date '2015-01-01', 10500, null  from dual union all
       select 2, date '2017-01-01', 20000, 10000 from dual union all
       select 2, date '2016-01-01', 21000, null  from dual union all
       select 2, date '2015-01-01', 22000, null  from dual       
     )
--  End of test data (not part of the solution). SQL query begins below this line.
select   refno, max(case when dt = :effective_date then amount2 end) as amount2
from     test_data
where    dt between add_months(:effective_date, -24) and :efffective_date
group by refno
having   max(amount1) > max(case when dt = :effective_date then amount2 end)
;

REFNO  AMOUNT2
-----  -------
    2    10000 

【讨论】:

    【解决方案2】:

    我无法为您提供直接答案,但肯定会帮助您获得正确答案。

    所以,基本上你需要学习—— GROUP BY 以及聚合函数 - http://www.w3schools.com/sql/sql_groupby.asp

    Group by 子句按 ref no 对结果进行分组,然后使用聚合函数 MAX

    DATE_ADD - http://www.w3schools.com/sql/func_date_add.asp sql query for getting data for last 3 months

    使用 DATE_ADD 添加最近 3 年间隔的条件

    【讨论】:

    • 请尝试提供完整的解决方案,而不仅仅是提供提示或指针。我不是反对者!
    • Oracle 中没有date_add()
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多