SQL查询早/晚日期

时间:2011-04-20 13:32:24

标签: sql oracle

我正在尝试根据最早和最晚日期的结果创建一个SQL视图。我知道min和max函数,但我无法正确实现它。到目前为止,我有:

select distinct
name,
study,
group,
ROUND (TLength * POWER (TWidth, 2) * 0.000523, 3) as Volume,
firstDate as firstDate,
lastDate as lastDate
from
(select
name,
study,
group,
min(operation_time) firstDate,
max(operation_time) lastDate,
MAX(DECODE (ACTIVITY,'length', RESULT_VALUE, NULL)) TLength,
MAX(DECODE (ACTIVITY,'width', RESULT_VALUE,NULL)) TWidth
from mx_all_data_vw
where mx_all_data_vw.study_name like '%MT%' 
group by name, group study);

这为我提供了最早或最晚日期的单行,以及最早和最晚日期的两列。

我想要2行,其中一行包含最早日期的所有数据,另一行包含最新日期的所有数据,而不是分隔早期和晚期日期的两列。

感谢。

1 个答案:

答案 0 :(得分:2)

简化了可读性:

SELECT  *
FROM    (
        SELECT  mx_all_data_vw.*,
                ROW_NUMBER() OVER (PARTITION BY name, study, "group" ORDER BY operation_time) rna,
                ROW_NUMBER() OVER (PARTITION BY name, study, "group" ORDER BY operation_time DESC) rnd,
                DECODE(activity, 'length', result_value, NULL) AS TLength,
                DECODE(activity, 'width', result_value, NULL) AS TWidth
        FROM    mx_all_data_vw
        WHERE   mx_all_data_vw.study_name like '%MT%'
        )
WHERE   1 IN (rna, rnd)

添加计算表达式而不是*