【问题标题】:Count distinct dates within timestamp by Month SQL按月 SQL 计算时间戳内的不同日期
【发布时间】:2020-09-27 23:43:41
【问题描述】:

我想计算每个月内不同日期的数量。

我有一个如下所示的数据集:

TIMESTAMP 
------------------
2017-10-25 14:39:51 
2017-10-25 15:00:51
2017-11-10 02:39:42
2018-09-24 14:39:55
2018-09-25 13:25:01
2019-02-12 12:23:44
...

所以我的预期输出是:

year_month | count
2017-10    2
2018-09    2
2019-02    1

到目前为止,我已经尝试了以下代码,但它返回的结果不正确:

WITH F AS(
    SELECT concat(YEAR(TIMESTAMP), MONTH(TIMESTAMP)) AS year_month
        FROM tbl
        WHERE TYPE = 'Site'
            AND TO_SITE = 'location'
)

SELECT count(year_month), year_month
    FROM F
    GROUP BY year_month

我不需要担心一天中的时间。我只想计算每个月不同的日子。提前感谢您的帮助。

【问题讨论】:

  • 解决方案取决于使用的数据库系统。每个都有自己的 SQL 方言。日期时间函数差异很大,尤其是。

标签: sql sql-server


【解决方案1】:

在 SQL Server 中,我会推荐以下方法之一:

select year(timestamp), month(timestamp), count(distinct convert(date, timestamp)
from t
group by year(timestamp), month(timestamp);

或者:

select format(timestamp, 'yyyy-MM'), count(distinct convert(date, timestamp))
from t
group by format(timestamp, 'yyyy-MM');

我认为不需要子查询或 CTE。

【讨论】:

    【解决方案2】:

    根据您的代码,我假设您使用的是 SQL Server,那么您可以执行类似的操作

    with cte as
    (
      select
        left(convert(varchar, myCol,112),6) as yyyy_mm,
        convert(date, myCol) as date
      from myTable
    )
    
    select 
      yyyy_mm,
      count(distinct date) as count
    from cte
    group by
      yyyy_mm
    

    输出:

    | yyyy_mm | count |
    *-----------------*
    | 201710  | 1     |
    | 201711  | 1     |
    | 201809  | 2     |
    | 201902  | 1     |
    

    【讨论】:

      【解决方案3】:

      PostgreSQL 中使用 date_trunc() 可以很简单:

      SELECT date_trunc('month', timestamp)
           , count(DISTINCT date_trunc('day', timestamp))
      FROM   tbl
      GROUP  BY 1;
      

      可能进行各种性能优化,具体取决于设置的详细信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-20
        • 2013-11-28
        • 2015-04-26
        • 1970-01-01
        • 2020-01-18
        • 1970-01-01
        • 2014-08-10
        • 1970-01-01
        相关资源
        最近更新 更多