SQL - 显示是否在另一条记录之后创建了一条记录

时间:2017-08-08 15:18:49

标签: sql ssms

我希望能够检查特定记录(在这种情况下,“under”是否已在创建初始记录后创建,并在单独的“under”或null中显示。

示例数据

Received    Name    Sub
01-Jun      Mike    Over
01-Jun      John    Over
02-Jun      Dave    Between
03-Jun      Pete    Over 
02-Jun      Mike    Under
03-Jun      Dave    Under

期望的结果

Received    Name    Sub     Sub2
01-Jun      Mike    Over    Under
01-Jun      John    Over    Null
02-Jun      Dave    Between Under
03-Jun      Pete    Over    Null

我正在使用这段代码,但它的错误让我无法再看到树木了。

DECLARE @TM DATETIME;
SET @TM = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');

select 
t1.received,
t1.name, 
t1.sub,
t2.sub as sub2

from 
dbo.tblOpen t1
join dbo.tblOpen t2 on t1.name = t2.name

where
t1.closed >= DATEADD(MONTH, -1, @TM)

请问我能否在正确的方向找到一点。

1 个答案:

答案 0 :(得分:3)

有很多方法可以解决这个问题。

相关子查询应该有效:

SELECT t1.received,
       t1.name, 
       t1.sub,
       CASE WHEN EXISTS (SELECT * 
                         FROM dbo.tblOpen t2 
                         WHERE t2.Name = t1.Name 
                         AND t2.received > t1.received 
                         AND t2.sub = 'UNDER') 
            THEN 'UNDER' 
      END AS sub2
FROM dbo.tblOpen t1
WHERE t1.sub <> 'UNDER'

LEFT JOIN

SELECT t1.received,
       t1.name, 
       t1.sub,
       t2.sub as sub2
FROM dbo.tblOpen t1
LEFT JOIN dbo.tblOpen t2 ON t2.Name = t1.Name 
                        AND t2.received > t1.received 
                        AND t2.sub = 'UNDER'
WHERE t1.sub <> 'UNDER'

根据您的实际数据,事情可能会变得更加复杂。例如,对于任何给定的名称,“UNDER”可以多次出现吗?如果是的话,你只想看一次,或每次出现一次吗?无论如何,根据您的样本数据,这是一个很好的起点。