2013-06-24 75 views
0

與相應的時間戳各個領域的多個最大值和最小值我有以下字段SQL服務器:在單行結果集

Field1(REAL), Field2(REAL), ...Fieldn(REAL), DateNTime(TimeStamp) 

在表table1 SQL Server表。

我該如何獲得以下結果集?即具有相應時間戳的每個字段的最大值和最小值

Max(Field1), Corresponding TimeStamp, Min(Field1), Corresponding TimeStamp, ..... 

其他字段類似。

感謝所有,

+0

哪個版本的SQLServer的是什麼? –

回答

1

最簡單的解決辦法是這樣的:

select 
    Field1_min, (select max(TimeStamp) from table1 where Field1 = Field1_min) as ts1min, 
    Field1_max, (select max(TimeStamp) from table1 where Field1 = Field1_max) as ts1max, 
    Field2_min, (select max(TimeStamp) from table1 where Field2 = Field2_min) as ts2min, 
    Field2_max, (select max(TimeStamp) from table1 where Field2 = Field2_max) as ts2max, 
    Field3_min, (select max(TimeStamp) from table1 where Field3 = Field3_min) as ts3min, 
    Field3_max, (select max(TimeStamp) from table1 where Field3 = Field3_max) as ts3max, 
    Field4_min, (select max(TimeStamp) from table1 where Field4 = Field4_min) as ts4min, 
    Field4_max, (select max(TimeStamp) from table1 where Field4 = Field4_max) as ts4max 
from (
    select 
     min(Field1) as Field1_min, max(Field1) as Field1_max, 
     min(Field2) as Field2_min, max(Field2) as Field2_max, 
     min(Field3) as Field3_min, max(Field3) as Field3_max, 
     min(Field4) as Field4_min, max(Field4) as Field4_max 
    from table1 
) S 
+0

感謝Markus,曾經使用過您的查詢,結果就是我們想要的。 – user2516142

2

通過使用窗口功能:

with cte as 
(select t.* 
     max(Field1) over() MaxField1, 
     min(Field1) over() MinField1, ... 
from Table1 t) 
select max(MaxField1) MaxField1, 
     max(case Field1 when MaxField1 then DateNTime end) MxF1DateTime, 
     min(MinField1) MinField1, 
     min(case Field1 when MinField1 then DateNTime end) MnF1DateTime, 
     ... 
from cte 
+0

謝謝Mark,查詢按我的意願工作。 – user2516142