SQL Server 2008查找最小日期

时间:2014-05-15 20:01:23

标签: sql sql-server sql-server-2008 date min

我希望MIN(日期)在每个组calendarID / structureID的范围内,并且具有-1值和14级。例如,calendarID 15555和StructureiD 20391将具有min(date)5/28/2014。

DAY TABLE

date        instruction grade  calendarID  structureID
5/27/2014        0          14   15555        20391
5/28/2014       -1          14   15555        20391
5/29/2014       -1          14   15555        20391
5/30/2014        0          14   15555        20391
8/14/2013       -1          14   15516        19996
8/15/2013       -1          14   15516        19996
8/16/2013       -1          14   15516        19996
8/19/2013       -1          14   15516        19996
8/20/2013       -1          14   15516        19996

2 个答案:

答案 0 :(得分:1)

SELECT MIN([date]) 
FROM [DAY] 
WHERE instruction = '-1' 
  AND grade = '14' 
GROUP BY calendarID
       , structureID

答案 1 :(得分:0)

以下是每行映射的结果

select a.*,b.mindate
from DayTable a
inner join 
(select calendarID,structureID,min([date]) as mindate
from DayTable
where instruction=-1 and grade=14
group by calendarID,structureID) b
on a.calendarID=b.calendarID and a.structureID=b.structureID

with b as
(select calendarID,structureID,min([date]) as mindate
from DayTable
where instruction=-1 and grade=14
group by calendarID,structureID)
select a.*,b.mindate
from DayTable a
inner join b
on a.calendarID=b.calendarID and a.structureID=b.structureID