Oracle SQL比较同一表的行

时间:2019-05-17 07:05:11

标签: sql oracle

表格:

Date         shopId        amount
17-MAY-19      1             100
17-MAY-19      2             20
16-MAY-19      2             20
17-APR-19      1             50

我需要根据要求找到同一张表中的那些记录:

给出日期,例如sysdate,找到每个shopId具有该日期的记录(每个shopId的日期是唯一的)以及30天之前的记录。

比较2条记录的数量,以查看diff的绝对百分比是否大于5(我在下面的代码中使用0.05代替%)。

如果2条记录都存在并且%diff匹配,则该记录应在结果集中。

对所有shopId执行此操作,然后返回结果集。

我能够检索记录,然后用后端语言(例如JAVA和PHP)进行比较,但是我想知道是否最好使用我不熟悉的SQL进行比较。

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 ) 

预期结果应该是:

Table:
shopId     Date1     amount1      Date2     amount2
  1      17-MAY-19    100       17-APR-19      50

请帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

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

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

Result

答案 1 :(得分:0)

联接的一种替代方法是使用LAG分析函数,例如:

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

这是否比联接版本快取决于您进行测试和决定。