如何获得上周(7天)oracle每天的记录数

时间:2018-05-04 08:55:04

标签: sql oracle date common-table-expression

你好我正在使用以下sql查询来获取过去24小时内每小时的记录数

WITH date_range
  AS (SELECT TRUNC(sysdate - (rownum/24),'HH24') as the_hour
        FROM dual
      CONNECT BY ROWNUM <= 24),
     the_data
  AS (SELECT TRUNC(systemdate, 'HH24')  AS log_date, count(*) AS num_obj
        FROM transactionlog where merchantcode='merc0003'
      GROUP BY TRUNC(systemdate, 'HH24'))   
SELECT TO_CHAR(dr.the_hour,'DD/MM/YYYY HH:MI AM'), NVL(trans_log.num_obj,0)
FROM date_range dr LEFT OUTER JOIN the_data  trans_log
     ON trans_log.log_date =  dr.the_hour
ORDER BY dr.the_hour DESC ;  

我试图在过去7天内每天在oracle中获得记录数 ..有人可以通过更改上述查询来指导我过去7天的工作吗?

我试着追踪过去7天,但还没有收获:

WITH date_range
  AS
(SELECT TRUNC(sysdate - (7)) as the_hour
        FROM dual
      CONNECT BY ROWNUM <= 7),
     the_data
  AS (SELECT TRUNC(systemdate, 'HH24')  AS log_date, count(*) AS num_obj
        FROM transactionlog where merchantcode='merc0003'
      GROUP BY TRUNC(systemdate, 'HH24'))   
SELECT TO_CHAR(dr.the_hour,'DD/MM/YYYY HH:MI AM'), NVL(trans_log.num_obj,0)
FROM date_range dr LEFT OUTER JOIN the_data  trans_log
     ON trans_log.log_date =  dr.the_hour
ORDER BY dr.the_hour DESC ; 

2 个答案:

答案 0 :(得分:0)

你的错误是你没有增加天数;你在同一天检索了七次。在当天添加level(或level - 1,无论哪个):

SELECT TRUNC(sysdate) - 7 + level AS the_hour
FROM dual
CONNECT BY ROWNUM <= 7

答案 1 :(得分:0)

我很惊讶你最初的CTE工作了。我没有听说过将CONNECT BYROWNUM一起使用(虽然做了一些谷歌搜索,我知道它在某些条件下有效。但我仍然相信这是一种误用)。要获得过去七天的日期范围,您需要以下内容:

WITH date_range AS (
    -- If you want to include today's date, add +1 to the date below
    SELECT TRUNC(SYSDATE - LEVEL) AS the_date
      FROM dual
   CONNECT BY LEVEL <= 7
)

将其与现有查询结合使用:

WITH date_range AS (
    SELECT TRUNC(SYSDATE - LEVEL) AS the_date
      FROM dual
   CONNECT BY LEVEL <= 7
), the_data AS (
    -- You still had 'HH24' here in the call to TRUNC()!
    SELECT TRUNC(systemdate) AS log_date, count(*) AS num_obj
      FROM transactionlog
     WHERE merchantcode = 'merc0003'
     GROUP BY TRUNC(systemdate)
)
SELECT dr.the_date, COALESCE(trans_log.num_obj, 0)
  FROM date_range dr LEFT JOIN the_data trans_log
    ON dr.the_date = trans_log.log_date
 ORDER BY dr.the_date DESC;

顺便说一下,你可以只为你的CTE使用别名;你不需要给它们全名只是为了再次别名它们。