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

2 回答 2

3

请参阅下面的 SQL Server 2005 代码示例,该示例使用 Miles D 的使用一系列 UNION'ed 选择的建议(抱歉,我不知道 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
于 2010-03-08T21:38:04.743 回答
1

我可以想到两种解决方案,但都需要考虑 Lucer 的评论以使用 IS NOT NULL,而不是 <> NULL。

  1. 创建一个两个用户定义的函数来返回最大值和最小值 - 好的,但假设您可以访问它。
  2. 使用一系列 UNION'ed 选择,每个选择六列中的一列,然后将其用作内部嵌套 SELECT,然后从中使用 SELECT MAX(), MIN()。
于 2010-03-05T10:04:50.367 回答