获取最后六个月的数据SQL Server

时间:2018-09-27 04:39:37

标签: sql-server

我已经尝试了许多已经在此处给出的查询,但是它也显示了上一年的数据,例如,如果使用此查询,

 Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)

DATEADD(m, -6, current_timestamp)

这些将在最近六个月产生。就我而言,我想打印最近六个月的数据。但是问题是这些查询是否会导致日期相同且年份不同的数据,例如(上面的查询返回的结果为'2018-03-27 10:04:52.537',并且如果有数据'2017-03-27 10:04:52.537'也将附带结果)。谁能帮我吗?

这是我的查询

DECLARE @date6MonthAgo DATETIME = DATEADD(m, -6, current_timestamp) 
DECLARE @totalCount INT = (SELECT COUNT(*) 
                           FROM   [PSA].[ProductionOrder] 
                           WHERE  CreatedDate >= @date6MonthAgo) 
DECLARE @openCount INT = (SELECT COUNT(*) 
                          FROM   [PSA].[ProductionOrder] 
                          WHERE  DocumentStatusCode=7 
                          AND    CreatedDate >= @date6MonthAgo ) 

SELECT @date6MonthAgo, @totalCount, @openCount

2 个答案:

答案 0 :(得分:2)

输入正确的ID列后,尝试执行类似的操作,只是为了自己确认返回的日期

DECLARE @date6MonthAgo DATETIME = DATEADD(m, -6, current_timestamp); 
SELECT  @date6MonthAgo;

SELECT CreatedDate, keycolumnID
FROM   [PSA].[ProductionOrder] 
WHERE  DocumentStatusCode=7 
AND    CreatedDate >= @date6MonthAgo 
ORDER BY CreatedDate;

答案 1 :(得分:1)

您可以使用它来查找当前日期以来的最近6个月的数据,

"GET/users/:id"

如果要从特定日期查找最近6个月的日期,可以在@fromdate和@todate参数中设置该日期,

DECLARE @fromdate as datetime, @todate as datetime

set @fromdate = (select DATEADD(month, -6, getdate()))
set @todate = getdate()

SELECT CreatedDate, keycolumnID
FROM   [PSA].[ProductionOrder] 
WHERE  DocumentStatusCode=7 
AND    cast(CreatedDate as date) between  cast(@fromdate as date) and  cast(@todate as date)
ORDER BY CreatedDate;