【问题标题】:Count for each day return wrong value每天计数返回错误值
【发布时间】:2021-07-08 03:32:51
【问题描述】:

以下代码每天计数 1,从今天(2021 年 4 月 13 日)到月底累加,周六、周日和工作日的总和。

;WITH mycte AS (
    SELECT  GETDATE() DateValue
    UNION ALL
    SELECT DateValue + 1
    FROM mycte
    WHERE DateValue < EOMONTH(dateadd(day,-1, getdate()))
)

select
   count(case when datepart(dw, DateValue) = 1 then 1 end) SunCount
 , count(case when datepart(dw, DateValue) = 7 then 1 end) SatCount
 , count(case when datepart(dw, DateValue) between 1 and 7 then 1 end) WeekCount
from mycte

对于今天(2021 年 4 月 13 日),我预计周六 = 2、周日 = 2 和工作日为 14,但到 4 月底我得到了 18 - 为什么?

【问题讨论】:

    标签: sql


    【解决方案1】:

    我认为这是因为 'between' 又包括 1 和 7,下面的查询应该给你剩余的 14 周天数

    ;WITH mycte AS (
        SELECT  GETDATE() DateValue
        UNION ALL
        SELECT DateValue + 1
        FROM mycte
        WHERE DateValue < EOMONTH(dateadd(day,-1, getdate()))
    )
    
    select
       count(case when datepart(dw, DateValue) = 1 then 1 end) SunCount
     , count(case when datepart(dw, DateValue) = 7 then 1 end) SatCount
     , count(case when datepart(dw, DateValue) between 2 and 6 then 1 end) WeekCount
    from mycte
    

    【讨论】:

    • 是的,我进行了更改并看到了您的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多