PL / SQL循环的唯一日期

时间:2018-10-31 07:56:34

标签: sql oracle plsql

我想为表中的日期使用for循环,它只关心年和月,而不是几天。

CURSOR ret_cur is SELECT orderdate FROM Orders WHERE status 
= 'DELAYED';
ret_rec ret_cur%ROWTYPE;

我目前有

insert into Orders(OrderId, CustomerId, RetailerId, ProductId, Count, 
UnitPrice, OrderDate, Status) values (2,2,1,10,45,60, 
to_date('20180102','YYYYMMDD'),'DELIVERED');

我的订单表中的此数据类型。 (以格式为例) 我想使用DISTINCT来迭代基于YYYY-MM的orderdate。 (不要打理日) 我尝试选择不同的to_char(orderdate,'YYYY-MM'),但我似乎无法正常工作。

例如,如果我有20180103、20180104、20180105,则应该是一次迭代,因为它们都具有相同的年月。

3 个答案:

答案 0 :(得分:0)

要选择没有时间的日子,可以tunc(sysdate)。几个月以来,我们必须group by一个char值:

select to_char(mydatecol,'yyyymm'), count(*) from
(
 select sysdate mydatecol from dual UNION ALL -- Fake-Table with some dates
 select sysdate - 1 mydatecol from dual UNION ALL
 select sysdate - 2 mydatecol from dual UNION ALL
 select sysdate - 3 mydatecol from dual UNION ALL
 select sysdate - 4 mydatecol from dual UNION ALL
 select sysdate - 30 mydatecol from dual UNION ALL
 select sysdate - 31 mydatecol from dual UNION ALL
 select sysdate - 32 mydatecol from dual UNION ALL
 select sysdate - 33 mydatecol from dual
)
group by to_char(mydatecol,'yyyymm')

结果:

201809  3
201810  6

答案 1 :(得分:0)

我认为您希望进行如下整理:

with Orders
    (
     OrderId, CustomerId, RetailerId, ProductId, 
     Count, UnitPrice, OrderDate, Status
     ) as
(
  select 2,2,1,10,45,60, to_date('20180102','YYYYMMDD'),'DELIVERED' from dual
)
select o.* 
  from Orders o 
 where to_char(OrderDate,'yyyy-mm') 
     = to_char(to_date('&myDate','yyyymmdd'),'yyyy-mm');

    -- for "myDate" substitution variable use 20180103 or 20180104 or 20180105 .. etc.

答案 2 :(得分:0)

执行这种查询的最佳方法是截断日期值:

SELECT CustomerId, trunc(OrderDate,'MM') OrderMonth
     , sum(Count) totalCount
     , sum(Count*UnitPrice) totalPrice
  FROM Orders 
 GROUP BY CustomerId, trunc(OrderDate,'MM')

例如...