【问题标题】:Oracle SQL query to get the difference value with two where clauseOracle SQL查询使用两个where子句获取差异值
【发布时间】:2020-01-10 03:35:14
【问题描述】:

我正在尝试查询 avg(score1+score2/2) 与 'current' 和最新的 'archived' 之间的差异。在 Oracle Apex 上做一个图表

表名:我的表

id | score1 | score2 | status | date
------------------------------------------
1  |   10   |   20   |  current|  07/09/19
2  |   20   |   30   |archived| 04/09/19
3  |   15   |   35   |archived| 02/09/19

想要结果:
(avg(score1 + score2/2) where status = 'current') - (avg(score1 + score2/2) where status = 'archived' only the most recent)

我试过了

【问题讨论】:

  • 样本数据期望的结果会有所帮助。

标签: sql oracle where-clause difference


【解决方案1】:

一种选择是使用

min/max(score1) keep (dense_rank first order by "date" desc) over (partition by status)

计算存档案例,以及当前案例的普通算术平均计算(根据样本数据,当前案例仅存在一行)

with myTable( id, score1, score2, status, "date" )as
(
 select 1, 10, 20, 'current' , date'2019-09-07' from dual union all
 select 2, 20, 30, 'archived', date'2019-09-04' from dual union all
 select 3, 15, 35, 'archived', date'2019-09-02' from dual 
), t as
(
 select
   case when status = 'current' then ( score1 + score2 ) / 2 end as curr,
   case when status = 'archived' then
   (
    (
     min(score1) keep (dense_rank first order by "date" desc) over (partition by status)+
     min(score2) keep (dense_rank first order by "date" desc) over (partition by status)
    )/2
   )
   end as arch
   from myTable
)
select max(curr)-max(arch) as "Avg.Result"
  from t;

Demo

【讨论】:

    【解决方案2】:

    你想要这个吗?

    select status , avg(score1 + score2/2) from you_table
    group by status
    

    select (select  avg(score1 + score2/2) from you_table
    where  status='current')-(select  avg(score1 + score2/2) from you_table
    where  status='archived') diff from dual
    

    【讨论】:

      【解决方案3】:

      嗯。 . .一种方法是条件聚合:

      select max(case when status = 'current' then score_avg end), as current_score,
             max(case when status = 'archive' then score_avg end), as last_archive_score,
             (max(case when status = 'current' then score_avg end) -
              max(case when status = 'archive' then score_avg end)
             ) as diff
      from (select t.*,
                   row_number() over (partition by status order by date desc) as seqnum,
                   (score1 + score2) / 2 as score_avg
            from t
           ) t
      where seqnum = 1;
      

      我猜你真的想要(score1 + score2) / 2)。但是,如果您想要 score1 + score2 / 2,请改用该表达式。

      【讨论】:

      • @paoloricardos 。 . .缺什么?代码没有明显的问题。
      猜你喜欢
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2011-07-13
      相关资源
      最近更新 更多