0

I have a SQL Server table with the following fields

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

in a table table1.

How can I get following resultset? i.e. max and min values of each field with corresponding timestamps

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

similarily for other fields.

Thanks All,

4

2 回答 2

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
于 2013-06-24T12:23:49.180 回答
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
于 2013-06-24T12:18:58.470 回答