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? ie max and min values of each field with corresponding timestamps
Max(Field1), Corresponding TimeStamp, Min(Field1), Corresponding TimeStamp, .....
similarily for other fields.
Thanks All,
By using windowed functions:
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
The simplest solution would be something like this:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.