2010-03-05 126 views
2

在以下查询中,开始/结束列是日期时间字段。从多个字段中选择最大/最小值

我应该如何修改这个查询来获得两个更多的列,一个是最小日期,另一个是最大日期(所有6个日期时间字段和所有行)在每一行中重复。

或者,我怎样才能创建一个新的查询,返回这些2(最小/最大)日期,当然是相同的结果集?

非常感谢! (我想为这两个SQL Server 2005和Sybase ASE的12.5.4答案)

select erg_mst.code, 
     erg_types.perigrafh, 
     erg_mst.FirstBaseStart, 
     erg_mst.FirstBaseFinish, 
     erg_mst.LastBaseStart, 
     erg_mst.LastBaseFinish , 
     erg_mst.ActualStart, 
     erg_mst.ActualFinish 
from erg_mst inner join 
     erg_types on erg_mst.type = erg_types.type_code 
where erg_mst.activemodule = 'co' 
and  (
      FirstBaseStart <> NULL OR 
      FirstBaseFinish <> NULL OR 
      LastBaseStart <> NULL OR 
      LastBaseFinish <> NULL OR 
      ActualStart <> NULL OR 
      ActualFinish <> NULL 
     ) 
order by isnull(FirstBaseStart,isnull(LastBaseStart,ActualStart)) 
+4

呃...不要使用'FirstBaseStart <> NULL',而是'FirstBaseStart IS NOT NULL',否则它将无法按预期工作,具体取决于ANSI NULL设置。 – Lucero 2010-03-05 09:32:39

+0

非常感谢,我会牢记这一点! – 2010-03-05 10:00:15

回答

1

我能想到的两种解决方案,但都将需要采取在船上Lucer的评论使用IS NOT NULL,而不是< > NULL。

  1. 创建一个两个用户定义的函数来返回最大值和最小值 - ok,但假定您有权访问它。
  2. 使用一系列UNION'ed选择,每一个选择六列中的一个,然后将其用作内部嵌套SELECT,然后在那里使用SELECT MAX(),MIN()。
3

请参阅以下使用使用一系列UNION'ed选择的万里D的建议SQL Server 2005的代码示例(对不起,我不知道的Sybase语法):

select min(AllDates) as MinDate, max(AllDates) as MaxDate 
from 
(
select erg_mst.FirstBaseStart as AllDates 
from erg_mst 
where erg_mst.activemodule = 'co' 
and  FirstBaseStart IS NOT NULL 
union all 
select erg_mst.FirstBaseFinish as AllDates 
from erg_mst 
where erg_mst.activemodule = 'co' 
and  FirstBaseFinish IS NOT NULL 
union all 
select erg_mst.LastBaseStart as AllDates 
from erg_mst 
where erg_mst.activemodule = 'co' 
and  LastBaseStart IS NOT NULL 
union all 
select erg_mst.LastBaseFinish as AllDates 
from erg_mst 
where erg_mst.activemodule = 'co' 
and  LastBaseFinish IS NOT NULL 
union all 
select erg_mst.ActualStart as AllDates 
from erg_mst 
where erg_mst.activemodule = 'co' 
and  ActualStart IS NOT NULL 
union all 
select erg_mst.ActualFinish as AllDates 
from erg_mst 
where erg_mst.activemodule = 'co' 
and  ActualFinish IS NOT NULL 
) #Temp