Sql select count仅在日期范围之间重复发生

时间:2016-06-20 09:56:21

标签: sql oracle oracle11g

Source Tables:
( MAILING )
| ID       | name     | dt        |
-----------------------------------
| 1        | foo      | 15-DEC-15 01.20.25.000000000 AM
| 2        | bar      | 16-DEC-15 01.20.25.000000000 AM

( OPEN )
| ID     | mailing  | dt        |
---------------------------------
| 1      | 1        | 15-DEC-15 03.20.25.000000000 AM
| 2      | 1        | 15-DEC-15 05.20.25.000000000 AM
| 3      | 2        | 16-DEC-15 03.20.25.000000000 AM

Expected result:
| name   | TOTAL     |    
----------------------
| foo    | 1         |
| bar    | 0         |  

从预期结果中可以看出,我必须计算在发送后不到24小时内重新打开的电子邮件。 现在计算发送后不到24小时开通的电子邮件我有:

                SELECT M.ID, COUNT(*) TOTAL
                    FROM MAILING.MAILING M

                LEFT JOIN MAILING.OPEN O
                    ON O.mailing = M.ID

                -- mailing between year 
                WHERE M.dt >= to_timestamp('01-Jan-2015', 'dd-MON-yyyy')
                    AND M.dt <= to_timestamp('31-Dec-2015', 'dd-MON-yyyy')

                    --  opened less than 24h after send
                    AND O.dt <= m.DATA_MAILING + INTERVAL '24' HOUR

                GROUP BY M.ID, M.name, M.dt

                ORDER BY M.dt ASC

感谢您的帮助和时间!

1 个答案:

答案 0 :(得分:1)

<强>查询

SELECT name,
       COUNT( opened_multiple ) AS total
FROM   (
  SELECT m.name,
         LAG( 1 ) OVER ( PARTITION BY mailing ORDER BY o.id ) AS opened_multiple
  FROM   mailing m
         LEFT OUTER JOIN
         open o
         ON (   m.id = o.mailing
            AND o.dt BETWEEN m.dt AND m.dt + INTERVAL '24' HOUR )
  WHERE  m.dt >= TIMESTAMP '2015-01-01 00:00:00'
  AND    m.dt <  TIMESTAMP '2016-01-01 00:00:00'
)
GROUP BY name;

<强>输出

NAME TOTAL
---- -----
foo      1
baa      0