Oracle SQL-如何检索今天与昨天之间的ID计数差异

时间:2019-10-07 10:52:14

标签: sql oracle date difference

我有一个表,用于捕获客户购买产品的时间。它会捕获唯一的购买ID以及购买时间的时间戳。

我想查询一下今天和昨天进行了多少次购买之间的区别?

不确定如何在oracle上查询吗?

3 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

select sum(case when trunc(datecol) = trunc(sysdate - 1) then 1 else 0 end) as num_yesterday,
       sum(case when trunc(datecol) = trunc(sysdate) then 1 else 0 end) as num_today,
       sum(case when trunc(datecol) = trunc(sysdate) then 1
                when trunc(datecol) = trunc(sysdate - 1) then -1
           end) as diff
from t
where datecol >= trunc(sysdate - 1);

答案 1 :(得分:0)

您可以使用“分组”功能将购买日与时间戳信息分组,并计算购买ID。

select trunc(purchase_ts) Day, count(purchase_id) Count
from purchase
group by trunc(purchase_ts)
order by 1 

答案 2 :(得分:0)

在该列上使用TRUNC将阻止Oracle在该列上使用索引(相反,您将需要一个单独的基于函数的索引);而是使用CASE语句测试日期是否在一天的开始和第二天的开始之间,然后COUNT在这些范围之间的值:

SELECT COUNT(
         CASE
         WHEN TRUNC( SYSDATE ) - INTERVAL '1' DAY <= your_date_column
         AND  your_date_coumn < TRUNC( SYSDATE )
         THEN 1
         END
       ) AS count_for_yesterday,
       COUNT(
         CASE
         WHEN TRUNC( SYSDATE ) <= your_date_column
         AND  your_date_coumn < TRUNC( SYSDATE ) + INTERVAL '1' DAY
         THEN 1
         END
       ) AS count_for_today
FROM   your_table
WHERE  TRUNC( SYSDATE ) - INTERVAL '1' DAY <= your_date_column
AND    your_date_coumn < TRUNC( SYSDATE ) + INTERVAL '1' DAY