Today Production - SQL 日期计算案例

Today Production - SQL Date Calculation case when

我有一个关于日期计算的问题。

我有一个名为 CreatedLocalTime 日期的日期时间列,格式如下:2015-11-15 19:48:50.000

我需要检索一个名为 Prod_Date 的新列:

if “CreatedLocalTime” between 
    (CreatedLocalTime 7 AM) 
    & (CreatedLocalTime+1 7 AM)
 return CreatedLocalTime date with DD/MM/YYYY format

换句话说,今天的产量=昨天早上7点到今天早上7点的总和。

使用案例有什么帮助吗?

对于day 7AMday+1 7AM,你可以试试:

SELECT CAST(CreatedLocalTime as date) 
...
FROM ...
WHERE ...
    CreatedLocalTime >= DATEADD(hour, 7, CAST(CAST(CreatedLocalTime as date) as datetime)) 
AND 
    CreatedLocalTime  < DATEADD(hour, 31, CAST(CAST(CreatedLocalTime as date) as datetime)) 
...

对于 previous day 7AMday 7AM,将 7 替换为 -14,将 31 替换为 7。

看起来你想要一些类似

的东西
DECLARE @StartDateTime Datetime 
DECLARE @EndDateTime Datetime 
SET @EndDateTime  = DATEADD(hour, 7,convert(datetime,convert(date,getdate())) )
SET @StartDateTime  = DATEADD(day, -1, @EndDateTime  )

--Print out the variables for demonstration purposes
PRINT '@StartDateTime = '+CONVERT(nchar(19), @StartDateTime,120)
PRINT '@EndDateTime   = '+CONVERT(nchar(19), @EndDateTime,120)

SELECT SUM (Production) AS Prod_Date FROM YourSchema.YourTable WHERE CreatedLocalTime >= @StartDateTime AND CreatedLocalTime < @EndDateTime

但是你也可以把它看成所有的时间,你从它们中删除 7 小时后都是昨天

SELECT SUM (Production) AS Prod_Date 
FROM YourSchema.YourTable 
WHERE DATEDIFF(day,DATEADD(hour, -7, CreatedLocalTime ))) = 1

第一个版本会更高效,因为查询只需要在开始时执行一次日期运算,而第二个版本涉及对每条记录执行 DATEDIFF 和 DATEADD。这在大量数据上会变慢。

镀金解决方案是向您的 table

添加一个计算列
ALTER TABLE YourSchema.YourTable ADD EffectiveDate AS CONVERT(date, DATEDIFF(day,DATEADD(hour, -7, CreatedLocalTime ))))

然后是该列的索引

CREATE INDEX IX_YourTable_EffectiveDate  ON YourSchema.YourTable (EffectiveDate )

所以你可以写

DECLARE @YesterDay date = DATEADD(day,-1, getdate())
SELECT SUM (Production) AS Prod_Date 
FROM YourSchema.YourTable 
WHERE EffectiveDate = @YesterDay

另一种方式..

SELECT  CASE WHEN CreatedLocalTime BETWEEN DATEADD(HOUR, 7,
                                                            CAST(CAST (CreatedLocalTime AS DATE) AS DATETIME))
                                            AND     DATEADD(HOUR, 31,
                                                            CAST(CAST (CreatedLocalTime AS DATE) AS DATETIME))
             THEN REPLACE(CONVERT(NVARCHAR, CreatedLocalTime, 103), ' ', '/')
        END AS CreatedLocalTime

如果需要,您可以为此编写 else 部分