每月平均天数的结果为空

时间:2019-06-17 13:56:07

标签: sql sql-server

select a.clientid, a.CaseType, b.EnrollmentStartDate, a.EligibilityStartDate, datediff(day, a.EligibilityStartDate, b.EnrollmentStartDate) as date_diff         
INTO ##temptable1 
FROM dbo.Client a, dbo.ClientEnrollment b
WHERE a.ClientId = b.ClientId 
AND a.CaseType = 99
ORDER BY a.ClientId



select avg (date_diff) from ##temptable1

因此,上述查询为我提供了从资格开始日期开始,客户注册程序所需的平均总天数。我现在想按每月排序结果

select avg (date_diff) from ##temptable1 
where EligibilityStartDate = '2019-03-01

由于某种原因,无论我指定的日期如何(即使原始查询产生超过40k的结果),我都将为NULL。我试图将EligibilityStartDate = '2019-03-01'插入表本身,但这也不起作用。 / p>

1 个答案:

答案 0 :(得分:2)

大概,您想要这样的东西:

SELECT YEAR(c.EligibilityStartDate) as yyyy,
       MONTH(c.EligibilityStartDate) as mm,
       AVG(DATEDIFF(DAY, c.EligibilityStartDate, ce.EnrollmentStartDate) as date_diff         
FROM dbo.Client c JOIN
     dbo.ClientEnrollment ce
     ON c.ClientId = ce.ClientId AND c.CaseType = 99
GROUP BY YEAR(c.EligibilityStartDate), MONTH(c.EligibilityStartDate)
ORDER BY YEAR(c.EligibilityStartDate), MONTH(c.EligibilityStartDate);

注意:

  • 从不FROM子句中使用逗号。
  • 始终使用正确的,明确的,标准 JOIN语法。
  • 使用有意义的表别名(即表名的缩写)而不是无意义的别名。
  • 您似乎想要一个聚合查询。