我有一个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记录,因为这是最近的价格变化。
答案 0 :(得分:1)
不确定您的要求是什么 - 但如果您只想要最上一行 - 那么请使用top:
select select top 1 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 post_dt desc, post_tm desc
答案 1 :(得分:1)
我添加了更多数据......如果是这样的情况..如果我按日期和时间订购我会得到221但价格没有变化 - user867621 4分钟前
如果价格没有变化,为什么系统会写下:
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
答案 2 :(得分:1)
您的查询基本上是:
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;
答案 3 :(得分:1)
要从该列表中获取id_1 = 217,并不是单独订购日期/时间DESC,因为该ID是"最近的第二个" C记录
所以,你可以使用ROW_NUMBER(),或使用TOP 2然后使用TOP 1
SELECT
*
FROM (
SELECT
id AS id_1
, item_no
, price
, post_dt
, post_tm
, aud_action
, ROW_NUMBER() OVER (ORDER BY post_dt DESC, post_tm DESC) AS Rn
FROM iminvaud_sql
WHERE item_no = '1-ADVENT ENGLISH'
AND aud_action = 'C'
ORDER BY
post_dt DESC, post_tm DESC
) sq
WHERE RN = 2
;
或
SELECT TOP 1
*
FROM (
SELECT TOP 2
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 = 'C'
ORDER BY
post_dt DESC, post_tm DESC
) sq
ORDER BY
post_dt ASC, post_tm ASC
;