找到2个特定行之间的差异

时间:2009-09-07 11:08:06

标签: sql oracle oracle9i

我需要找到2个特定行之间的区别,但不能破解LAG / LEAD函数,也不确定这些函数是否有用。

需要从dest = OM-OM_20的行中减去dest = OM-OM_225的行。

使用Oracle 9i。

表格使用:

创建
SELECT TRUNC(DATETIME,'HH') DATETIME,decode(OBJECT_ID,20,'OM-OM_20',225,'OM-OM_225',250,'OM-PSTN','OM-INT') DEST,

sum(BO) as CAABS,
SUM(BA+ RE) as CATT,
round(SUM((AC/22)*11,2) as CAMIN

FROM SCHEMA.TABLE
WHERE ((OBJECT_ID = 20) or  (OBJECT_ID = 225)  or (OBJECT_ID = 250) or (OBJECT_ID = 150) or (OBJECT_ID =160) or (OBJECT_ID = 161) or (OBJECT_ID = 162)  or (OBJECT_ID = 163) or (OBJECT_ID = 164) or (OBJECT_ID = 165) or(OBJECT_ID = 166)  or (OBJECT_ID = 167) ) 
and DATETIME between trunc(sysdate,'hh')-1/24 and trunc(sysdate,'hh')-1/24/3600
group by TRUNC(DATETIME,'HH'), decode(OBJECT_ID,20,'OM-OM_20',225,'OM-OM_225',250,'OM-PSTN','OM-INT')
order by 1 desc

输出

DATETIME                      DEST    CAABS           CATT           CAMINS

9/7/2009 1:00:00 PM OM-INT    10417           64670          87971.67
9/7/2009 1:00:00 PM OM-PSTN   7372            95388          13309.17
9/7/2009 1:00:00 PM OM-OM_20   6767             231884           184952.5
9/7/2009 1:00:00 PM OM-OM_225     33104           101003             68570.83

2 个答案:

答案 0 :(得分:0)

SELECT  SUM(DECODE(OBJECT_ID, 20, BO, -BO))
FROM    mytable
WHERE   OBJECT_ID IN (20, 225)
        AND DATETIME BETWEEN TRUNC(SYSDATE, 'HH') - 1 / 24 AND TRUNC(SYSDATE, 'hh') - 1 / 24 / 3600
GROUP BY
        TRUNC(DATETIME, 'HH')

答案 1 :(得分:0)

如果要在同一个选择中执行此操作,可以使用连接:

select T1.some_field - coalesce(T2.some_field, 0),
...
from TABLE T1
left join TABLE T2 on T2.dest = 'OM-OM_225' and T1.dest = 'OM-OM_20'

(查询的具体形式可能因DB而异)