【问题标题】:Cumulative count on date data from datetime format日期时间格式的日期数据的累积计数
【发布时间】:2020-09-17 16:55:29
【问题描述】:

我有一张桌子看起来像:

ID entry_time
abc123 2020-05-29 10:29:18.000
def456 2020-05-30 13:12:43.000
...

我想按日期进行累积计数,所以我做了:

select entry_time, count (*) OVER (ORDER BY entry_time) as TOTAL_NUM from my_table;

没关系,但会以datetime 格式计算。我只想指望date(即白天,不在乎时间)。

我该怎么做?

非常感谢,

【问题讨论】:

  • 你用的是哪个sql引擎?
  • 在您的结果集中,您想要datetime 的一行(如在您的原始表格中),还是date 的一行?
  • 你看过这个similar Q吗?

标签: sql date group-by count window-functions


【解决方案1】:

您可以使用 convert 或 cast entry_time 为 Date

select entry_time, count (*) OVER (ORDER BY Convert(date,entry_time)) as TOTAL_NUM from my_table;

OR

select entry_time, count (*) OVER (ORDER BY Cast(entry_timeas as date)) as TOTAL_NUM from my_table;

【讨论】:

    【解决方案2】:

    如果你想要每天一条记录,你可以使用聚合和窗口函数:

    select
        date(entry_time) entry_day,
        sum(count(*)) over(order by date(entry_time)) total_num
    from mytable
    group by date(entry_time)
    order by entry_day
    

    这假定您的数据库支持date(),它将datetime 转换为date(例如在MySQL 中)。如果没有,它肯定有另一种方法来做到这一点。

    【讨论】:

      【解决方案3】:

      您可以尝试将entry time 转换为日期。

      select 
          convert(date, entry_time) as entry_time, 
          count (*) OVER (ORDER BY convert(date, entry_time)) as total_num 
      from my_table;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-16
        • 1970-01-01
        • 2021-06-09
        • 2017-10-12
        • 2019-07-15
        • 1970-01-01
        • 2011-03-03
        • 1970-01-01
        相关资源
        最近更新 更多