如何比较SQL中的行

时间:2014-01-30 12:18:21

标签: sql-server-2008

我正在尝试比较2行,我很难做到这一点。

我有这些行:

Name                StartDate                  EndDate
Ian Buckley     2009-10-30 00:00:00.000     2014-01-09 00:00:00.000
Ian Buckley     2014-01-10 00:00:00.000     NULL
Neil Kent       2009-10-17 00:00:00.000     2014-01-09 00:00:00.000
Neil Kent       2014-01-10 00:00:00.000     NULL

我要做的是检查每个名字,如果StartDate(在EndDate null的行上)在EndDate之后(在实际的行上) EndDate

  

例如:Ian Buckley 2014-01-10 00:00:00.000> 2014-01-09 00:00:00.000   那没关系。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

尝试此查询:

SELECT      *, (CASE WHEN t1.StartDate > t2.EndDate THEN 'Ok' ELSE 'Not Ok' END) AS isOk
FROM        dbo.TABLE_1 AS t1
LEFT JOIN   dbo.TABLE_1 AS t2 ON t2.name = t1.name AND t2.EndDate IS NOT NULL

WHERE t1.EndDate IS NULL

答案 1 :(得分:0)

加入你的桌子。您必须确保每一行都会因为它自身而导致连接条件。我通常会添加一个t1.primary_key <> t2.primary_key

Select t1.*, t2.* from yourtable t1 
inner join yourtable t2 on t1.name = t2.name and t2.endDate is null 
     and t2.StartDate > t1.enddate