查询谁是第一个和第二个项目的工作

时间:2011-12-13 19:30:06

标签: sql sql-server-2000

我有一个看起来像这样的表:

Id (PK, int, not null)
ReviewedBy (nvarchar(255), not null)
ReviewDateTime(datetime, not null)
Decision_id (int, not null)
Item_id (FK, int, not null)

此表的业务流程是每个Item(由Item_id外键显示)将由2个人处理。

如何查询此表格以确定谁(ReviewedBy)首先审核了该项目以及谁先审核了该项目。

我真的很难弄清楚这一点,因为我忽略了在我的表中添加Type列,以确定用户的行为。 :(

修改

鉴于以下数据

Id,ReviewedBy,ReviewedWhen,SomeOtherId,
16,111111,2011-12-14 22:06:54,1,
17,187935,2011-12-14 22:07:03,1,
18,187935,2011-12-14 22:07:18,2,
19,187935,2011-12-14 22:07:20,3,
20,111111,2011-12-14 22:07:23,2,
21,187935,2011-12-14 22:07:26,3,
22,123456,2011-12-14 22:27:50,4,

with schema

CREATE TABLE [Reviews] (
[Id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,
[ReviewedBy] NVARCHAR(6)  NOT NULL,
[ReviewedWhen] TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
[SomeOtherId] INTEGER  NOT NULL
);

执行以下操作以获取进行第二次审核的人员列表,将返回只有SomeOtherId的一次审核的行。

select t1.*
from Reviews as t1
  left outer join Reviews as t2
    on (t1.SomeOtherId = t2.SomeOtherId and t1.ReviewedWhen < t2.ReviewedWhen)
where t2.SomeOtherId is null;

解决方案

-- First checks
select t1.ReviewedBy, count(t1.Id)
from Reviews as t1
  left outer join Reviews as t2
    on (t2.SomeOtherId = t1.SomeOtherId and t1.ReviewedWhen > t2.ReviewedWhen)
where          t2.SomeOtherID is null
group by t1.ReviewedBy;

-- Second checks
select t1.ReviewedBy, count(t1.Id)
from Reviews as t1
  left outer join Reviews as t2
    on (t2.SomeOtherId = t1.SomeOtherId and t1.ReviewedWhen < t2.ReviewedWhen)
where          t2.SomeOtherID is null
and  t1.Id not in (select Id from Reviews group by SomeOtherId having count(SomeOtherId) = 1)
group by t1.ReviewedBy;

基本上,它只计算了第一次和第二次检查时只有一次检查的项目。我所要做的就是确保当我计算第二次检查时,我不包括只有一次检查的行。

我认为我可以在一个查询中实现这一点,但不要猜测。

1 个答案:

答案 0 :(得分:2)

试试这个:

select 
t1.ReviewedBy FirstReviewer,
t2.ReviewedBy SecondReviewer
from
Table t1
left outer join Table t2 on t1.Item_Id = t2.Item_Id and t2.ReviewDateTime > t1.ReviewDateTime

如果您只想返回已由两个人审核的行,请将左外部联接更改为内部联接。

如果ReviewDateTime永远不会更新且Id是标识列,您可以将连接更改为Id而非ReviewDateTime,这将更快。