根据当前日期和上一个日期显示数量之和

时间:2015-05-20 08:38:52

标签: sql sql-server

在下面的查询中,我试图根据当前日期和上一个日期得到数量的总和。在我的情况下,它不工作它显示null但值存在于表中。我预期的结果是

Quantity | Date
200      | 20-5-2015
15       | 19-5-2015

Select SUM(RecommentedQuantity) FROM IndentDetails ID
LEFT OUTER JOIN Indent I On I.IndentID=ID.IndentID
WHERE ID.CreatedOn =GETDATE()
UNION

Select SUM(RecommentedQuantity) FROM IndentDetails ID
LEFT OUTER JOIN Indent I On I.IndentID=ID.IndentID
WHERE ID.CreatedOn =       dateadd(d, datediff(d, 0, GETDATE())-1, 0) 

2 个答案:

答案 0 :(得分:1)

尝试此查询:

<div class="col-3">
  <div class="videoThum">
    <a href="javascript:;" rel="https://www.youtube.com/embed/OSgvYZpO2xY" class="youTubeVideo">
      <img src="http://s8.postimg.org/jf407d2xh/saina_nehwal_syed.png" />
    </a>
  </div>
  <div class="caption"><a href="#"><h2>2015 Syed Modi International</h2></a>
    <a href="#">
      <p>2015 Syed Modi International India Masters SF [WS]</p>
    </a>
  </div>
</div>

答案 1 :(得分:1)

您获得NULL的原因是因为在您的WHERE子句ID.CreatedOn =GETDATE()中,GETDATE()CreatedOn都有一个不匹配的时间组件。

您可以像这样重写您的查询。

Select SUM(RecommentedQuantity) FROM IndentDetails ID
LEFT OUTER JOIN Indent I On I.IndentID=ID.IndentID
WHERE ID.CreatedOn >= CONVERT(DATE,GETDATE()) AND ID.CreatedOn < CONVERT(DATE,DATEADD(D,1,GETDATE()))
UNION

Select SUM(RecommentedQuantity) FROM IndentDetails ID
LEFT OUTER JOIN Indent I On I.IndentID=ID.IndentID
    WHERE ID.CreatedOn >= CONVERT(DATE,DATEADD(D,-1,GETDATE())) AND ID.CreatedOn < CONVERT(DATE,GETDATE())

或单个查询

Select CONVERT(DATE,ID.CreatedOn),SUM(RecommentedQuantity)
FROM IndentDetails ID
LEFT OUTER JOIN Indent I On I.IndentID=ID.IndentID
WHERE ID.CreatedOn >= CONVERT(DATE,DATEADD(D,-1,GETDATE())) AND ID.CreatedOn < CONVERT(DATE,DATEADD(D,1,GETDATE()))
GROUP BY CONVERT(DATE,ID.CreatedOn)

如果您使用的是SQL Server 2005,则可以使用CONVERT(VARCHAR(10),ID.CreatedOn,112)代替CONVERT(DATE,ID.CreatedOn)