如何比较SQL Server查询中的日期范围?

时间:2018-04-06 11:03:30

标签: sql sql-server

假设我在这样的表中有数据:

| DateTimePurchased    | Amount |
|----------------------|--------|
| 1/1/2017  3:23:15 PM | 657    |
| 1/1/2017  3:38:29 PM | 730    |

我想运行一个像这样输出的查询:

| Day   | 2017_Total | 2018_Total |
|-------|------------|------------|
| Jan 1 | 4354653    | 7686787    |
| Jan 2 | 3453634    | 6546456    |

等...

我如何编写SQL Server查询?

2 个答案:

答案 0 :(得分:3)

我会这样说:

select month(DateTimePurchased) as mm, day(DateTimePurchased) as dd,
       sum(case when year(DateTimePurchased) = 2017 then amount end) as total_2017,
       sum(case when year(DateTimePurchased) = 2018 then amount end) as total_2018
from t
group by month(DateTimePurchased), day(DateTimePurchased)
order by mm, dd;

这会将“日期”拆分为两列,一列是月份,另一列是白天。这实际上使得结果更容易使用,因为您可以更轻松地对结果进行排序。

答案 1 :(得分:0)

Gordon Linoffs的回答是正确的。

以下查询为您提供了您所要求的内容。

SELECT (LEFT(DATENAME(MONTH, GETDATE()),3)) + ' ' + CAST((DAY(DATE_ADDED)) AS NVARCHAR(10)) AS [Day], SUM(CASE WHEN YEAR(DATE_ADDED) = 2017 THEN AMOUNT END) AS [2017_Total], SUM(CASE WHEN YEAR(DATE_ADDED) = 2018 THEN AMOUNT END) AS [2018_Total] FROM TBLDATE GROUP BY MONTH(DATE_ADDED), DAY(DATE_ADDED) ORDER BY [Day]