对不起,新手在这里。
与此类似:SQL: retrieve only the records whose value has changed
我想了解如何包含第一行?带*'s?
的行ID description eaudittimestamp
-- ----------- -----------------------
777012 above 2017-03-27 10:09:59.330 *
777012 above 2017-03-27 10:09:58.550
777012 below 2017-03-27 10:26:03.560 *
777012 below 2017-03-27 10:36:02.423
777012 below 2017-03-27 10:37:15.250
777012 middle 2017-03-27 10:49:11.680 *
777012 middle 2017-03-27 10:49:18.870
777013 something 2017-03-27 11:49:18.870
777013 something 2017-03-27 12:49:18.870
777014 nodescription 2017-03-27 12:49:18.870
道歉,我是新来的。让我改一下。我有一个表,它有ID,描述和时间戳。与审计表类似。如何查找描述已更改的行(包括第一行)。
如何排除只有1行的那些?即777013和777014?
答案 0 :(得分:1)
with ct as
(
select Code, Date, Rate,
row_number() over (partition by Code, Rate order by Code, Date) as rn
from your_table
)
select Code, Date, Rate
from ct
where rn = 1
order by Code, Date;
<强>更新强>
declare @foo table(ID int, description varchar(100), eaudittimestamp datetime); insert into @foo values (777012, 'above', '2017-03-27 10:09:59.330'), (777012, 'above', '2017-03-27 10:09:58.550'), (777012, 'below', '2017-03-27 10:26:03.560'), (777012, 'below', '2017-03-27 10:36:02.423'), (777012, 'below', '2017-03-27 10:37:15.250'), (777012, 'middle', '2017-03-27 10:49:11.680'), (777012, 'middle', '2017-03-27 10:49:18.870'), (777013, 'something', '2017-03-27 11:49:18.870'), (777013, 'something', '2017-03-27 12:49:18.870'), (777014, 'nodescription', '2017-03-27 12:49:18.870'); with ct as ( select ID, description, eaudittimestamp, row_number() over (partition by ID, description order by eaudittimestamp) rn, count(*) over (partition by ID) as ct from @foo ) select ID, Description, eaudittimestamp from ct where rn = 1 and ct > 1; GO
ID | Description | eaudittimestamp -----: | :---------- | :------------------ 777012 | above | 27/03/2017 10:09:58 777012 | below | 27/03/2017 10:26:03 777012 | middle | 27/03/2017 10:49:11 777013 | something | 27/03/2017 11:49:18
dbfiddle here
答案 1 :(得分:1)
对于您提供的数据,row_number()
有效:
select t.*
from (select t.*,
row_number() over (partition by id, description order by eaudittimestamp) as seqnum
from t
) t
where seqnum = 1;
每个id
/ description
对返回一行。最低eaudittimestamp
的那个。这似乎是你想要的。
编辑:
如果要排除一行的组,只需使用另一个窗口函数:
select t.*
from (select t.*,
row_number() over (partition by id, description order by eaudittimestamp) as seqnum,
min(description) over (partition by id) as min_d,
max(description) over (partition by id) as max_d
from t
) t
where seqnum = 1 and min_d <> max_d;