Oracle-按日期分组

时间:2019-06-18 01:53:14

标签: sql oracle oracle11g

我在Oracle 11g数据库中有一个这样的表

TABLE REC
REC_ID NUMBER
CARD_ID NUMBER
REC_STATUS NUMBER
REC_DATE TIMESTAMP

我想知道在给定期间内已充值多少张卡,但是我希望此信息按日期分组。 如果一个日期已经计算出card_id,则不应在下一个(另一个)计算出card_id。

这里有一些测试数据

with
     REC ( REC_ID, CARD_ID, REC_STATUS, REC_DATE ) as (
       select '1', '100', '1', SYSTIMESTAMP - 5 from dual union all
       select '2', '100', '1', SYSTIMESTAMP - 5  from dual union all
       select '3', '200', '1', SYSTIMESTAMP - 5  from dual union all
       select '4', '100', '1', SYSTIMESTAMP - 4  from dual union all
       select '5', '300', '1', SYSTIMESTAMP - 4  from dual union all
       select '6', '200', '1', SYSTIMESTAMP - 4  from dual union all
       select '7', '100', '1', SYSTIMESTAMP - 3  from dual union all
       select '8', '400', '1', SYSTIMESTAMP - 3  from dual union all
       select '9', '400', '1', SYSTIMESTAMP - 3  from dual union all
       select '10', '400', '1', SYSTIMESTAMP - 2  from dual union all
       select '11', '300', '1', SYSTIMESTAMP - 2  from dual union all
       select '12', '100', '1', SYSTIMESTAMP - 2  from dual union all
       select '13', '400', '1', SYSTIMESTAMP - 2  from dual 
     )
-- end of test data

当我执行这样的查询时,我的总数为4,这是正确的。

SELECT  
    COUNT(DISTINCT CARD_ID) COUNT 
FROM REC 
WHERE REC_STATUS = 1

结果

|COUNT|
|   4 |

但是,当我尝试这种方式时,我的总数为10。 这是因为当我在日期上使用“ group by”并在ID中使用“ distinct”时,区别仅适用于分组日期,不适用于整个期间。

SELECT  
    TRUNC(REC_DATE) DAT, 
    COUNT(DISTINCT CARD_ID) COUNT
FROM REC 
WHERE REC_STATUS = 1
GROUP BY TRUNC(REC_DATE)

结果

DAT      | COUNT
14/06/19 |   2
13/06/19 |   3
15/06/19 |   3
12/06/19 |   2

我该怎么做才能将差异应用于期间总计,但仍按日期保留分组?

1 个答案:

答案 0 :(得分:0)

也许您只想要每张卡的最早日期:

SELECT TRUNC(MIN_REC_DATE) as DAT, 
        COUNT(*) as COUNT
FROM (SELECT CARD_ID, MIN(REC_DATE) as MIN_REC_DATE
      FROM REC
      WHERE REC_STATUS = 1 
      GROUP BY CARD_ID
     ) R
GROUP BY TRUNC(MIN_REC_DATE);