SQL MIN和MAX只有一行时

时间:2013-06-21 14:55:09

标签: sql sql-server sql-server-2008

我的查询中有2行,用于从表中选择最小值和最大值。返回最多只有2行,但是如果只返回1行,我不希望第二行返回任何内容。

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 个答案:

答案 0 :(得分: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