【问题标题】:My count CTE returning blanks, how can I get it return as 0?我的计数 CTE 返回空白,我怎样才能让它返回为 0?
【发布时间】:2021-06-27 00:42:35
【问题描述】:

创建 CTE 以计算从今天到当月月底的剩余天数。所以我今天(2021 年 3 月 30 日)的报告不包括明天的 2021 年 3 月 31 日。

   declare @DespatchTo Date = '03-30-2021'

   WITH mycte AS
    (
      SELECT CAST(Convert(date,getdate()) AS DATETIME) DateValue
      UNION ALL
      SELECT  DateValue + 1
      FROM    mycte   
      WHERE   DateValue  < DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @DespatchTo) + 1, 0)) --03-31-2021
    )
    
    SELECT SUN.Count as SunCount, SAT.Count as SatCount, WK.Count as WeekCount
    FROM 
    (SELECT  count(*) as Count
    FROM    mycte
    WHERE DatePart("w",DateValue) = 1
    group by DatePart("w",DateValue))
    As SUN,
    
    (SELECT  count(*) as Count
    FROM    mycte
    WHERE DatePart("w",DateValue) = 7
    group by DatePart("w",DateValue))
    As SAT,
    
    (SELECT  distinct SUM(COUNT(*)) OVER() AS Count
    FROM    mycte
    WHERE DatePart("w",DateValue) > 1 AND DatePart("w",DateValue) < 7
    group by DatePart("w",DateValue))
    As WK

返回空白/空结果。我怎样才能返回为 0?

【问题讨论】:

  • @GordonLinoff SQL Server,不过我在 ssrs 中运行查询

标签: sql sql-server tsql reporting-services


【解决方案1】:

这是你需要做的:

;WITH mycte AS (
    SELECT  GETDATE() DateValue
    UNION ALL
    SELECT DateValue + 1
    FROM mycte
    WHERE DateValue < EOMONTH(GETDATE())
)

select
   count(case when datepart(dw, DateValue) = 1 then 1 end) SUN
 , count(case when datepart(dw, DateValue) = 7 then 1 end) SAT
 , count(case when datepart(dw, DateValue) between 2 and 6 then 1 end) WK
from mycte

如果要排除今天,可以调整 cte :

;WITH mycte AS (
    SELECT  GETDATE() + 1 DateValue
    WHERE GETDATE() <> EOMONTH(GETDATE())
    UNION ALL
    SELECT DateValue + 1
    FROM mycte
    WHERE DateValue < EOMONTH(GETDATE())
)

select
   count(case when datepart(dw, DateValue) = 1 then 1 end) SUN
 , count(case when datepart(dw, DateValue) = 7 then 1 end) SAT
 , count(case when datepart(dw, DateValue) between 2 and 6 then 1 end) WK
from mycte

【讨论】:

  • 今天出于某种原因。它给了我一周多 4 天的时间?
  • 间隔天数不对。查看更新的答案
  • 感谢修复,我有一个问题,当我的日期为 03-31-2021 时,工作日计数为 1,但应该为 0?
  • 这取决于你想要的帽子,他们查询上面显示的给定日期直到月底的工作日、星期日和星期六有多少天,对于 2021 年 3 月 31 日,这是一个weekday ,为此执行 1 ,如果您想排除今天的日期,您可以在 cte 中执行此操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多