【问题标题】:Count record based on dates like 0 to 7 days 7 to 14 days and 14 to 28 days根据日期计数记录,例如 0 到 7 天、7 到 14 天和 14 到 28 天
【发布时间】:2021-10-22 17:36:09
【问题描述】:

我有一个包含三列 IDstatusCreateDate 的表。我想根据 createdate 从表中计数

仅过去 0-7 天、7-14 天、14-28 天和 28-35 天...

【问题讨论】:

  • 请发布一些数据和预期结果。

标签: sql oracle date


【解决方案1】:

使用如下所示的示例表:

SQL> select trunc(sysdate) today from dual;

TODAY
----------
21.08.2021

SQL> with temp as
  2    (select id, createdate, trunc(sysdate) - createdate diff_days
  3     from test
  4    )
  5  select * from temp
  6  order by createdate desc;

        ID CREATEDATE  DIFF_DAYS
---------- ---------- ----------
         1 20.08.2021          1
         2 19.08.2021          2
         3 13.08.2021          8
         4 12.08.2021          9
         5 02.08.2021         19
         6 26.07.2021         26

6 rows selected.

SQL>

你可以这样做(注意你的时期不正确;同一行不能(或者,我应该说:不应该)属于两个时期。它不能是 0-7如果日期差 正好 7 天,则为 7-14。它要么在第一个时期,要么在第二个时期,而不是两者。

SQL> with temp as
  2    (select id, createdate, trunc(sysdate) - createdate diff_days
  3     from test
  4    )
  5  select
  6    sum(case when diff_days >= 0 and diff_days  <  7 then 1 else 0 end) " 0- 6 days",
  7    sum(case when diff_days >= 7 and diff_days  < 14 then 1 else 0 end) " 7-13 days",
  8    sum(case when diff_days >= 14 and diff_days < 21 then 1 else 0 end) "14-20 days",
  9    sum(case when diff_days >= 21 and diff_days < 28 then 1 else 0 end) "21-27 days"
 10  from temp;

 0- 6 days  7-13 days 14-20 days 21-27 days
---------- ---------- ---------- ----------
         2          2          1          1

SQL>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多