2013-06-21 91 views
0

我的查詢中有2行選擇表中的最小值和最大值。只返回最多2行,但如果只返回1行,我不想爲第二行返回任何內容。SQL MIN和MAX只有一行時

IE:

MAX(CASE WHEN bd.DayText = 'Tuesday' and bd.BookingDuration = 3 
and CONVERT(time(0), bd.StartTime) < CONVERT(time(0), '12:00:00') 
AND bd.NoOfHOurs < 5.5 and s.PrimarySchool = 1 THEN bd.ID ELSE NULL END) 
"TuesdayHourlyAM", 

MIN(CASE WHEN bd.DayText = 'Tuesday' and bd.BookingDuration = 3 
and CONVERT(time(0), bd.StartTime) < CONVERT(time(0), '12:00:00') 
AND bd.NoOfHOurs < 5.5 and s.PrimarySchool = 1 THEN bd.ID ELSE NULL END) 
"TuesdayHourlyAM2",  

所以,如果那裏有返回1行,TuesdayHourlyAM2應該返回null。

任何想法?

感謝

回答

1

嘗試在case聲明其包裝:

(case when count(*) > 1 
     then MIN(CASE WHEN bd.DayText = 'Tuesday' and bd.BookingDuration = 3 and 
         CONVERT(time(0), bd.StartTime) < CONVERT(time(0), '12:00:00') AND 
         bd.NoOfHOurs < 5.5 and s.PrimarySchool = 1 
        THEN bd.ID ELSE NULL 
       END) 
end) as TuesdayHourlyAM2