2

我正在尝试使用 CASE 语句,但没有得到想要的答案。

这是代码:

DECLARE @Table TABLE (DocID INT, DocNumber VARCHAR(10),DocDevStat INT, MilestoneDate DATETIME,  
                      MilestoneID INT) 
INSERT INTO @Table VALUES (30, '14-1', 6, '10-01-2001', 10) 
INSERT INTO @Table VALUES (30, '14-1', 6, '10-15-2001', 11) 
INSERT INTO @Table VALUES (30, '14-1', 6, '11-06-2002', 13) 
INSERT INTO @Table VALUES (30, '14-1', 6, '11-01-2003', 27) 
INSERT INTO @Table VALUES (30, '14-1', 6, '11-01-2003', 30) 
INSERT INTO @Table VALUES (30, '14-1', 6, '03-01-2004', 28) 
INSERT INTO @Table VALUES (30, '14-1', 6, '03-01-2004', 35) 
INSERT INTO @Table VALUES (31, '14-3', 2, '06-27-2003', 10) 
INSERT INTO @Table VALUES (31, '14-3', 2, '05-05-2004', 27) 
INSERT INTO @Table VALUES (31, '14-3', 2, '05-05-2004', 30) 
INSERT INTO @Table VALUES (31, '14-3', 2, '07-20-2005', 35) 
INSERT INTO @Table VALUES (31, '14-3', 2, '08-31-2005', 32) 
INSERT INTO @Table VALUES (36, '1-2', 7, '10-01-1996', 10) 
INSERT INTO @Table VALUES (36, '1-2', 7, '10-01-1996', 11) 
INSERT INTO @Table VALUES (36, '1-2', 7, '12-01-1996', 28) 
INSERT INTO @Table VALUES (36, '1-2', 7, '12-01-1996', 35) 

Select distinct t.Docid, t.DocNumber,

case when t.DocDevStat IN (6,7,8) and t.MilestoneID = 35 then Max(t.Milestonedate)
     when t.DocDevStat IN (2,3,4) then Convert(date,GETDATE()) end AS LatestDate

FROM @Table t
Group By t.DocID, t.DocNumber, t.DocDevStat, t.MilestoneID

我得到的结果是:

Docid      DocNumber    LatestDate
30         14-1           NULL
30         14-1           2004-03-01 
31         14-3           2012-10-17 
36          1-2           NULL
36          1-2           1996-12-01 

但我想得到:

Docid      DocNumber    LatestDate
30         14-1           2004-03-01 
31         14-3           2012-10-17 
36          1-2           1996-12-01 

在这种情况下使用 CASE 语句正确的技术吗?

4

1 回答 1

3
Select DISTINCT t.Docid, t.DocNumber,
case when t.DocDevStat IN (6,7,8) then Max(t.Milestonedate)
when t.DocDevStat IN (2,3,4) then Convert(date,GETDATE()) end AS LatestDate
FROM @Table t
where t.DocDevStat IN (2,3,4) OR (t.DocDevStat IN (6,7,8) and t.MilestoneID = 35)
Group By t.DocID, t.DocNumber, t.DocDevStat, t.MilestoneID

此查询返回您正在查找的数据。我将您要搜索的条件添加到 where 子句中。

于 2012-10-18T18:31:19.527 回答