ProjID Dno RNo Status DateApproved
100 1 1 Initiated 2014-12-31 09:15:58.000
100 1 1 Approved 2015-01-31 09:15:58.000
100 1 1 Approved 2015-02-01 09:15:58.000
100 1 1 Approved 2015-05-28 09:15:58.000
100 1 1 Approved 2015-06-20 09:15:58.000
101 1 1 Approved 2014-12-31 09:15:58.000
101 1 1 Approved 2015-01-31 09:15:58.000
101 1 1 Approved 2015-02-01 09:15:58.000
101 1 1 Approved 2015-05-28 09:15:58.000
101 1 1 Approved 2015-08-20 09:15:58.000
在上面的示例中,我必须为每个项目获得最多(Dateapproved)作为Dateapproved。 如果所有修订状态都在特定组中被批准,例如:项目ID = 101,其组中的所有行都具有已批准的状态,因此我必须获得最大日期:' 2015-08-20 09:15 :58.000'。但是对于Projectid = 100,一个状态仍处于启动状态,因此我们必须将Null显示为Dateapproved。
先谢谢
我的输出应该是:
ProjId Dno Rno DateApproved
100 1 1 NUll
101 1 1 2015-08-20 09:15:58.000
示例代码:
Create table #temp(
ProjectID varchar(35),
Documentno int,
Revisionno int,
Status varchar(35),
DateApproved Datetime)
insert into #temp values ( '100', 1, 1, 'Initiated','2014-12-31 09:15:58')
insert into #temp values ( '100', 1, 1, 'Approved','2015-01-31 09:15:58 ')
insert into #temp values ( '100', 1, 1, 'Approved','2015-02-01 09:15:58 ')
insert into #temp values ( '100', 1, 1, 'Approved','2015-05-28 09:15:58 ')
insert into #temp values ( '100', 1, 1, 'Approved','2015-06-20 09:15:58 ')
insert into #temp values ( '101', 1, 1, 'Approved','2014-12-31 09:15:58 ')
insert into #temp values ( '101', 1, 1, 'Approved','2015-01-31 09:15:58 ')
insert into #temp values ( '101', 1, 1, 'Approved','2015-02-01 09:15:58 ')
insert into #temp values ( '101', 1, 1, 'Approved','2015-05-28 09:15:58 ')
insert into #temp values ( '101', 1, 1, 'Approved','2015-08-20 09:15:58 ')
select * from #temp
答案 0 :(得分:2)
试试这个:
SELECT T.ProjectID,
Documentno as Dno,
Revisionno as RNo,
CASE WHEN SUM(CASE WHEN T.Status <> 'Approved' THEN 1 ELSE 0 END) = 0
THEN Max(T.DateApproved) ELSE NULL
END as DateApproved
from #temp T
GROUP BY T.ProjectId, Documentno , Revisionno
在针对您的测试数据运行时,它会提供以下输出:
PROJECT ID DNo TNo DateApproved
100 1 1 NULL
101 1 1 2015-08-20 09:15:58.000
答案 1 :(得分:1)
您可以使用case语句和条件聚合执行此操作。使用Approved
获取非COUNT(NULLIF(Status, 'Approved'))
的状态计数。如果这是0,那么获得批准的最大日期:
SELECT ProjectID,
DateApproved = CASE WHEN COUNT(NULLIF(Status, 'Approved')) = 0 THEN MAX(DateApproved) END
FROM #Temp
GROUP BY ProjectID;