Oracle SQL比较同一表的行

Oracle SQL比较同一表的行,sql,oracle,Sql,Oracle,表: 预期结果应为: select * from table t1 inner join table t2 on t1.shopId = t2.shopId WHERE t1.ordertime = sysdate and t2.ordertime = sysdate - 30 and abs( (t1.amount - t2.amount) / t2.amount > 0.05 ) 请帮助,谢谢。您应该在sysdate上使用函数,因为sysdate始终包含当前日期和

表:

预期结果应为:

select * 
from table t1 
inner join table t2 on t1.shopId = t2.shopId 
WHERE t1.ordertime = sysdate 
  and t2.ordertime = sysdate - 30 
  and abs( (t1.amount - t2.amount) / t2.amount > 0.05 ) 
请帮助,谢谢。

您应该在sysdate上使用函数,因为sysdate始终包含当前日期和时间

Table: shopId Date1 amount1 Date2 amount2 1 17-MAY-19 100 17-APR-19 50
连接的替代方法是使用滞后分析函数,例如:

with tab as(
  select to_date('17.05.2019','dd.mm.yyyy') as dat, 1 as shopid, 100 as amount from dual union all
  select to_date('17.05.2019','dd.mm.yyyy') as dat, 2 as shopid, 20 as amount from dual union all
  select to_date('16.05.2019','dd.mm.yyyy') as dat, 2 as shopid, 20 as amount from dual union all
  select to_date('17.04.2019','dd.mm.yyyy') as dat, 1 as shopid, 50 as amount from dual 

)

select * 
from tab t1 
join tab t2 on t1.shopid = t2.shopid 
WHERE t1.dat = trunc(sysdate)
  and t2.dat = trunc(sysdate - 30)
  and (t1.amount - t2.amount) / t2.amount > 0.05

这是否比join版本快取决于您的测试和决定。

是否有错误?或者从查询中获得意外结果集?无错误,但意外结果:没有返回的记录SysDate同时包含日期和时间组件。你可能会想要TRUNCSYSDATE。试试看会发生什么。我不明白,你需要两张记录,一张是现在的,一张是30天以前的,还是过去30天的所有记录?@PiotrKamoda一张是现在的,一张是30天以前的
with tab as(
  select to_date('17.05.2019','dd.mm.yyyy') as dat, 1 as shopid, 100 as amount from dual union all
  select to_date('17.05.2019','dd.mm.yyyy') as dat, 2 as shopid, 20 as amount from dual union all
  select to_date('16.05.2019','dd.mm.yyyy') as dat, 2 as shopid, 20 as amount from dual union all
  select to_date('17.04.2019','dd.mm.yyyy') as dat, 1 as shopid, 50 as amount from dual 

)

select * 
from tab t1 
join tab t2 on t1.shopid = t2.shopid 
WHERE t1.dat = trunc(sysdate)
  and t2.dat = trunc(sysdate - 30)
  and (t1.amount - t2.amount) / t2.amount > 0.05
WITH your_table AS (SELECT to_date('17.05.2019','dd.mm.yyyy') dt, 1 shopid, 100 amount FROM dual UNION ALL
                    SELECT to_date('17.05.2019','dd.mm.yyyy') dt, 2 shopid, 20 amount FROM dual UNION ALL
                    SELECT to_date('16.05.2019','dd.mm.yyyy') dt, 2 shopid, 20 amount FROM dual UNION ALL
                    SELECT to_date('17.04.2019','dd.mm.yyyy') dt, 1 shopid, 50 amount FROM dual)
SELECT shopid,
       date1,
       amount1,
       date2,
       amount2
FROM   (SELECT shopid,
               dt date1,
               amount amount1,
               LAG(dt) OVER (PARTITION BY shopid ORDER BY dt) date2,
               LAG(amount) OVER (PARTITION BY shopid ORDER BY dt) amount2
        FROM   your_table
        WHERE  dt IN (TRUNC(SYSDATE), TRUNC(SYSDATE) - 30))
WHERE  amount1 > amount2 * 1.05;

    SHOPID DATE1          AMOUNT1 DATE2          AMOUNT2
---------- ----------- ---------- ----------- ----------
         1 17/05/2019         100 17/04/2019          50