分析函数 SQL

问题描述 投票:0回答:1

我请求帮助解决有关分析/聚合查询的问题。 有一个val值变化的表。 价值可能会改变,但我可能不会。 我正在计算该值最后一次更改的日期。 (在示例中为 5)。

with part_table as(
select src_table.* 
, lag(val) over (partition by id order by nday) prev_val
, lead(val) over (partition by id order by nday) nex_val
from 
  (
  select 1 id, 'value1' val, 1 nday from dual union all
  select 1 id, 'value2' val, 2 nday from dual union all
  select 1 id, 'value1' val, 3 nday from dual union all
  select 1 id, 'value2' val, 4 nday from dual union all
  select 1 id, 'value1' val, 5 nday from dual union all
  select 1 id, 'value1' val, 6 nday from dual union all
  select 1 id, 'value1' val, 7 nday from dual 
  ) src_table
) select 
  t.* 
  ,(select max(nday) from part_table t2 where t2.id=t.id and t2.val <> t2.prev_val) max_nday
from part_table t
order by id, nday

我有一个问题,我不明白如何在窗口中没有子查询的情况下做到这一点...... 毕竟,不可能将条件传递给聚合函数,对吗?

with part_table as(
select src_table.* 
, lag(val) over (partition by id order by nday) prev_val
, lead(val) over (partition by id order by nday) nex_val
, max(nday) over (partition by id order by nday) max_nday --- how to get 5?
from 
  (
  select 1 id, 'value1' val, 1 nday from dual union all
  select 1 id, 'value2' val, 2 nday from dual union all
  select 1 id, 'value1' val, 3 nday from dual union all
  select 1 id, 'value2' val, 4 nday from dual union all
  select 1 id, 'value1' val, 5 nday from dual union all
  select 1 id, 'value1' val, 6 nday from dual union all
  select 1 id, 'value1' val, 7 nday from dual 
  ) src_table
) select 
  t.* 
from part_table t
order by id, nday
sql aggregate-functions
1个回答
0
投票

根据您的描述,您的sql似乎不必要地复杂。我认为你可以简单地解决这个问题,无需所有工会:

create table #src_table (
    id int, 
    nday int, 
    [value] int, 
    primary key (id))
insert into #src_table values 
    (1, 1, 1),
    (2, 2, 2),
    (3, 3, 3),
    (4, 4, 3),
    (5, 5, 4), -- last day with a change
    (6, 6, 4),
    (7, 7, 4)


;with cte as (
    select
        nday,
        isnull([value] - lag([value]) over (order by id), 0) as IsChanged
    from #src_table 
    ) 
select max(nday) 
from cte
where cte.IsChanged = 1

这里的结果是

5
- 最后一天有变化。

© www.soinside.com 2019 - 2024. All rights reserved.