Where子句中的Datepart计算

时间:2017-07-07 19:12:59

标签: sql sql-server

我遇到查询的Where子句中的datepart计算问题。查询返回结果而不进行计算,但如果添加条件,则无效。

DECLARE @StatusId INT;
SELECT @StatusId = Id FROM company.Status WHERE Name = 'Signed' AND CompanyId = 1;

SELECT FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd') AS newDate, 
    SUM(CASE WHEN cont.UpdatedDate IS NOT NULL THEN 1 ELSE 0 END) AS TotalSignedLeads
FROM client.testw cont
WHERE cont.CompanyId = 1  
    AND cont.AffiliateId = 1
    AND cont.CreatedDate BETWEEN '7-01-2017' AND '7-09-2017' 
    AND DATEPART(dw, cont.CreatedDate) NOT IN (1, 7) //This causes problem.
    AND cont.StatusId = @StatusId 
GROUP BY CAST(cont.CreatedDate AS DATE)
ORDER BY newDate ;

This is the data above query gives without the datepart condition.  
newDate  TotalSignedLeads
07/08    7

2 个答案:

答案 0 :(得分:2)

好吧,因为您将cont.CreatedDate作为日期放在查询的顶部,我怀疑它实际上是varchar ...因此您需要

...
and datepart(weekday, cast(cont.CreatedDate as date)) not in (1,7)
...

bad-habits-to-kick-using-shorthand-with-date-time-operations

如果您没有收到错误,那么您就没有符合该条件的行。也许您的DATEFIRST设置不是您认为的。

另外,不确定GROUP BY CAST(@StatusId.CreatedDate AS DATE)是什么意思......

答案 1 :(得分:0)

我怀疑你想要一个更像这样的查询:

SELECT FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd') AS newDate, 
       COUNT(cont.UpdatedDate) AS TotalSignedLeads
FROM client.testw cont
WHERE cont.CompanyId = 1 AND
      cont.AffiliateId = 1 AND
      cont.CreatedDate BETWEEN '2017-07-01' AND '2017-09-01' AND
      DATEPART(dw, CAST(cont.CreatedDate AS DATE)) NOT IN (1, 7) AND //This causes problem.
      cont.StatusId = @StatusId 
GROUP BY FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd')
ORDER BY newDate ;

的变化:

  • 比较日期采用标准格式,因此应正确解释。
  • GROUP BY使用与列SELECT相同的结构。
  • SUM(CASE)被更简单的COUNT()替换。
  • CreatedDate的值被投放为DATE。说实话,我不确定会解决任何问题,因为无论如何都应该发生这种情况。