每周开放订单的数量

时间:2014-03-28 01:49:45

标签: mysql datetime

我试图查找每周开放的订单数量。每周开放的订单应包含在每周开放的计数中。数据类似于下面的

id  open_dt               close_dt
1   2014-01-01 07:00:00   2014-01-01 07:00:00 
2   2014-01-01 07:00:00   2014-01-02 07:00:00 
3   2014-01-02 07:00:00   2014-01-09 07:00:00 
4   2014-01-08 07:00:00   NULL 

NULL close_dt计为仍然打开,应该在打开后的每周出现

我的查询如下所示,但它不会返回我期待的数字:

SELECT YEAR(open_dt) AS year, WEEK(open_dt) AS week, count(*) 'open'
FROM table
WHERE open_dt >= week(open_dt)
OR 
(
    close_dt > week(open_dt)
    OR close_dt IS NULL
)
GROUP BY YEAR(open_dt), WEEK(open_dt)

我试图获得如下结果:

year  week  open
2014  1     3
2014  2     2
2014  3     1
...

感谢任何提示或指导。

1 个答案:

答案 0 :(得分:1)

这种情况有助于拥有日历表或周列表。我假设你每周至少开一次:

select yw.y, yw.w, count(t.open_dt) as "Open"
from (select distinct year(open_dt) as y, week(open_dt) as w,
             year(open_dt) * 100 + week(open_dt) as yw
      from table t
     ) yw left outer join
     table t
     on yw.yw >= year(open_dt)*100 + week(open_dt) and
        (yw.yw <= year(close_dt)*100 + week(close_dt) or close_dt is null)
group by yw.y, yw.w
order by yw.y, yw.w;