我有一个SQL表,它是一个审计线索。我正在尝试获取最近一次价格更改的时间。
使用此查询,我有以下数据
select id as id_1
,item_no, price
,post_dt
,post_tm
,aud_action
from iminvaud_sql
where item_no = '1-ADVENT ENGLISH'
and aud_action in ('B','C')
order by id desc
id_1 item_no price post_dt post_tm aud_action
221 1-ADVENT ENGLISH 2.000000 2014-08-18 00:00:00.000 1900-01-01 10:19:35.113 C
218 1-ADVENT ENGLISH 2.000000 2014-08-18 00:00:00.000 1900-01-01 10:19:35.110 B
217 1-ADVENT ENGLISH 2.000000 2014-08-18 00:00:00.000 1900-01-01 10:01:47.163 C
216 1-ADVENT ENGLISH 3.000000 2014-08-18 00:00:00.000 1900-01-01 10:01:46.757 B
59 1-ADVENT ENGLISH 3.000000 2013-08-19 00:00:00.000 1900-01-01 13:23:32.950 C
58 1-ADVENT ENGLISH 1.000000 2013-08-19 00:00:00.000 1900-01-01 13:23:32.890 B
系统为更改前写一个B,为更改写一个C,因此在某种意义上说B和C记录是分组的。对于此示例,我想获得217条记录,因为它是最近的价格变化。
您的查询本质上是:
select s.*
from iminvaud_sql s
where s.item_no = '1-ADVENT ENGLISH' and s.aud_action in ('B','C')
order by id desc;
据我所知,“ B”和“ C”没有添加任何信息。相反,让我们看一下最近出现的价格的第一次出现。我将以此为基础id
。如果价格是单调的(始终增加或减少),则以下方法将起作用:
select top 1 s.*
from iminvaud_sql s
where exists (select 1
from iminvaud_sql s2
where s2.item_no = s.item_no and s2.aud_action in ('B','C') and s2.price = s.price
) and
s.aud_action in ('B','C') and s.item_no = '1-ADVENT ENGLISH'
order by s.id_1 asc;
如果不是这种情况,则可以使用技巧。诀窍是利用价格之间的差异row_number()
并按row_number()
价格进行划分。差异的最大值将是最近的价格。
select top 1 s.*
from (select s.*,
(row_number() over (order by id_1) -
row_number() over (partition by price order by id_1)
) as pricegroup
from iminvaud_sql s
where s2.aud_action in ('B','C') and s.item_no = '1-ADVENT ENGLISH'
) s
order by price_group, s.id_1 asc;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句