如何在sql中将每月数据转换为Bi每周数据

时间:2017-11-06 07:06:18

标签: sql oracle

使用以下查询我获取每月数据(登录详细信息),现在尝试获取每周一次。我正在尝试转换它,需要你的帮助。

每月我喜欢这个,它在我的查询/代码中工作:

SELECT t.m_name as Title, COUNT(p.id) as Logins
FROM M_LOGINRECORD l, M_MUSER mu, M_PERSON p, M_TITLETYPE t
WHERE trunc(logintime, 'MM')= TRUNC(ADD_MONTHS(SYSDATE, -6),'MM'

我每周都会尝试类似下面的内容,有人可以建议吗?

SELECT t.m_name as Title, COUNT(p.id) as Logins
FROM M_LOGINRECORD l, M_MUSER mu, M_PERSON p, M_TITLETYPE t
WHERE trunc(logintime, 'DD')= to_char(sysdate +10,'dd/mm/yyyy')
group by t.m_name,trunc(logintime, 'DD');

谢谢,

1 个答案:

答案 0 :(得分:1)

  

我每周都会尝试类似下面的内容,有人可以建议吗?

要获得每周群组,您可以使用TRUNC( datevalue, 'IW' ),它将截断到ISO周的开始(星期一午夜):

SELECT t.m_name as Title,
       COUNT(p.id) as Logins
FROM   M_LOGINRECORD l
       CROSS JOIN M_MUSER mu
       CROSS JOIN M_PERSON p
       CROSS JOIN M_TITLETYPE t  -- Did you really mean this rather than INNER JOIN?
WHERE  logintime >= TRUNC( SYSDATE + 10, 'IW' )
AND    logintime <  TRUNC( SYSDATE + 10, 'IW' ) + INTERVAL '1' WEEK
GROUP BY
       t.m_name,
       TRUNC( logintime, 'IW' ); -- This is redundant given the WHERE clause.

要获得两周的小组,您可以从参考点中减去日期(例如:TRUNC( DATE '1970-01-01', 'IW' ),包含1970-01-01的ISO周的开始),这将为您提供天数差异;然后除以14并将数字置于最后,以给出自该参考点以来的两周完整周期数;然后乘以14并加回到参考点以获得当前两周时间段的开始:

SELECT t.m_name as Title,
       TRUNC( DATE '1970-01-01', 'IW' )
       + FLOOR( ( logindate - TRUNC( DATE '1970-01-01', 'IW' ) ) / 14 ) ) * 14
           AS two_week_period_start,
       COUNT(p.id) as Logins
FROM   M_LOGINRECORD l
       CROSS JOIN M_MUSER mu
       CROSS JOIN M_PERSON p
       CROSS JOIN M_TITLETYPE t  -- Did you really mean this rather than INNER JOIN?
GROUP BY
       t.m_name,
       TRUNC( DATE '1970-01-01', 'IW' )
       + FLOOR( ( logindate - TRUNC( DATE '1970-01-01', 'IW' ) ) / 14 ) ) * 14