2010-03-05 97 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 
相關問題