2015-05-26 64 views
0

我与列和值以下SQL选择问题

Date     Nbr NewValue OldValue 
5/20/2015 14:23:08 123 abc  xyz 
5/20/2015 15:02:10 123 xyz  abc 
5/21/2015 08:10:02 123 xyz  pqr 
5/21/2015 10:10:05 456 lmn  ijk 

表从上面的表格,我想选择5/21/2051234565/21/2015。我不想选择5/20nbr 123因为在这一天结束时OldValueNewValue没有变化。

如何写SELECT语句的这种要求。

+3

您的数据是否也有时间部分(分钟等)或其他东西如何实际确定相同日期和nbr行的顺序? –

+0

嗯..只需使用日期(没有时间),您的前两行的顺序就不会得到保证......还应该有某种标识列,以便您可以正确地整理出您需要的结果 –

+0

什么在这里呢?如何知道哪一行对应于一天结束? –

回答

0

如果您使用至少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]; 
+0

真棒乔。有效。感谢您的帮助。 – user28455

0
SELECT * FROM YOURTABLE AS T1 
INNER JOIN YOURTABLE AS T2 ON T1.NBR=T2.NBR AND T1.OLDVALUE<>T2.NEWVALUE 

内加入你的表本身

+0

没有工作。它仍在显示所有数据。 – user28455

+0

你有主键在表 如果你刚才添加“ T1.ID <> T2.ID”,将工作 – RASKOLNIKOV

0

我这个问题的理解是,你只想用新的数据选择行,其中不存在条款

IF TABLE1.OLDVALUE <> TABLE2.OLDVALUE; 
BEGIN 
SELECT DISTINCT NBR 
FROM [TABLENAME] AS TABLE1 
INNER JOIN [TABLENAME] AS TABLE2 ON TABLE1.NBR = TABLE2.NBR 
WHERE DATE = '5/21/2015' -- I recommend using sysdate here but your choice 
END; 
0

使用:

选择(从[表]选择* b其中a.nbr = b.nbr和b.newvalue = a.oldvalue)从[表] “日期”,NBR,其中不存在