如果您使用至少SQL Server 2008中,你可以用一个CTE来确定哪些条目表示每个[Nbr]
的每一天中的第一项和条目代表过去的,然后比较两个,看看实际根据其他一些答案中的建议,使用自联接发生了更改。例如:
-- Sample data from the question.
declare @TestData table ([Date] datetime, [Nbr] int, [NewValue] char(3), [OldValue] char(3));
insert @TestData values
('2015-05-20 14:23:08', 123, 'abc', 'xyz'),
('2015-05-20 15:02:10', 123, 'xyz', 'abc'),
('2015-05-21 08:10:02', 123, 'xyz', 'pqr'),
('2015-05-21 10:10:05', 456, 'lmn', 'ijk');
with [SequencingCTE] as
(
select *,
-- [OrderAsc] will be 1 if and only if a record represents the FIRST change
-- for a given [Nbr] on a given day.
[OrderAsc] = row_number() over (partition by convert(date, [Date]), [Nbr] order by [Date]),
-- [OrderDesc] will be 1 if and only if a record represents the LAST change
-- for a given [Nbr] on a given day.
[OrderDesc] = row_number() over (partition by convert(date, [Date]), [Nbr] order by [Date] desc)
from
@TestData
)
-- Match the original value for each [Nbr] on each day with the final value of the
-- same [Nbr] on the same day, and get only those records where an actual change
-- has occurred.
select
[Last].*
from
[SequencingCTE] [First]
inner join [SequencingCTE] [Last] on
convert(date, [First].[Date]) = convert(date, [Last].[Date]) and
[First].[Nbr] = [Last].[Nbr] and
[First].[OrderAsc] = 1 and
[Last].[OrderDesc] = 1
where
[First].[OldValue] != [Last].[NewValue];
您的数据是否也有时间部分(分钟等)或其他东西如何实际确定相同日期和nbr行的顺序? –
嗯..只需使用日期(没有时间),您的前两行的顺序就不会得到保证......还应该有某种标识列,以便您可以正确地整理出您需要的结果 –
什么在这里呢?如何知道哪一行对应于一天结束? –