CASE声明或类似技术

时间:2012-10-18 16:46:36

标签: sql-server-2008 case

我正在尝试使用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语句正确的技术?

1 个答案:

答案 0 :(得分: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子句中。