2

我正在尝试稍微完善这个问题,因为我上次并没有真正正确地提问。我本质上是在做这个查询:

Select count(orders)
From Orders_Table
Where Order_Open_Date<=To_Date('##/##/####','MM/DD/YYYY')
and Order_Close_Date>=To_Date('##/##/####','MM/DD/YYYY')

其中##/##/#### 是同一天。本质上,此查询旨在查找任何给定日期的“未平仓”订单数量。唯一的问题是我想在一年或更长时间的每一天都这样做。我想如果我知道如何将 ##/##/#### 定义为变量,然后按该变量对计数进行分组,那么我可以让它工作,但我不知道该怎么做——或者那里也可能是另一种方式。我目前在 SQL 开发人员上使用 Oracle SQL。感谢您的任何意见。

4

3 回答 3

0

您可以使用这样的“行生成器”技术(针对 Hogan 的评论进行编辑)

Select RG.Day,
       count(orders)
From   Orders_Table,
      (SELECT trunc(SYSDATE) - ROWNUM as Day
       FROM  (SELECT 1 dummy FROM dual)
       CONNECT BY LEVEL <= 365
      ) RG
Where RG.Day              <=To_Date('##/##/####','MM/DD/YYYY')
  and RG.Day              >=To_Date('##/##/####','MM/DD/YYYY')
  and Order_Open_Date(+)  <= RG.Day
  and Order_Close_Date(+) >= RG.Day - 1
Group by RG.Day
Order by RG.Day

这应该列出上一年的每一天以及相应的订单数量

于 2013-05-14T06:49:45.590 回答
0

Lets say you had a table datelist with a column adate

aDate
1/1/2012
1/2/2012
1/3/2012

Now you join that to your table

Select *
From Orders_Table 
join datelist on Order_Open_Date<=adate and Order_Close_Date>=adate

This gives you a list of all the orders you care about, now you group by and count

Select aDate, count(*)
From Orders_Table 
join datelist on Order_Open_Date<=adate and Order_Close_Date>=adate
group by adate

If you want to pass in a parameters then just generate the dates with a recursive cte

with datelist as
(
   select @startdate as adate
   UNION ALL
   select adate + 1
   from datelist
   where (adate + 1) <= @lastdate
)
Select aDate, count(*)
From Orders_Table 
join datelist on Order_Open_Date<=adate and Order_Close_Date>=adate
group by adate

NOTE: I don't have an Oracle DB to test on so I might have some syntax wrong for this platform, but you get the idea.

NOTE2: If you want all dates listed with 0 for those that have nothing use this as your select statement:

Select aDate, count(Order_Open_Date)
From Orders_Table 
left join datelist on Order_Open_Date<=adate and Order_Close_Date>=adate
group by adate
于 2013-05-14T03:31:04.567 回答
-1

如果你只想要一天,你可以TRUNC像这样查询

select count(orders)
From orders_table
where trunc(order_open_date) = to_date('14/05/2012','dd/mm/yyyy')
于 2013-05-14T05:45:18.657 回答