我有简单的SQL Server视图,我需要修改它:
CREATE VIEW [dbo].[ApplicantStat]
AS SELECT ISNULL(CONVERT(VARCHAR(50), NEWID()), '') AS Pkid,
AVG(ApplicationTime) AS 'AvgApplicationTime',
AVG(ResponseTime) AS 'AvgResponseTime',
CAST(ROUND(100.0 * count(case when [IsAccepted] = 1 then 1 end) / count(case when [IsValid] = 1 then 1 end), 0) AS int) AS 'AcceptRate'
FROM [Application]
它按计划运行,但我需要为其添加日期范围。它并不像Where>那么简单。这个日期和<那个日期,我需要创建一个范围。
假设我的Application表中有' CreatedOn' 日期。我希望能够包括上一整天(昨天)的所有行,并且可以回溯30天(包括)。
我正在使用SQL Server 2014。
答案 0 :(得分:1)
使用:
CAST
请注意使用{{1}},这是因为要花一整天忽略时间部分。
答案 1 :(得分:1)
您应该能够在最后添加WHERE
BETWEEN
条款。
CREATE VIEW [dbo].[ApplicantStat]
AS SELECT ISNULL(CONVERT(VARCHAR(50), NEWID()), '') AS Pkid,
AVG(ApplicationTime) AS 'AvgApplicationTime',
AVG(ResponseTime) AS 'AvgResponseTime',
CAST(ROUND(100.0 * count(case when [IsAccepted] = 1 then 1 end) / count(case when [IsValid] = 1 then 1 end), 0) AS int) AS 'AcceptRate'
FROM [Application]
WHERE CreatedOn BETWEEN GETDATE()-1 AND GETDATE()-30
答案 2 :(得分:1)
这样的事情:
where MyColumn between dateadd(dd, -1, convert(date, getdate())) and dateadd(dd, -30, convert(date, getdate()))
答案 3 :(得分:0)
这有点超出了这个问题的范围,但对某些人来说可能有用。我喜欢这种创建具有日期范围的表的方式,以便在查询中使用:
USE MyDataBase
DECLARE @StartDate DATE
DECLARE @EndDate DATE
SET @StartDate = '2014-01-01' -- << user input >> --
SET @EndDate = '2036-12-31' -- << user input >> --
IF OBJECT_ID ('TEMPDB..#Date') IS NOT NULL DROP TABLE #Date
IF OBJECT_ID ('TEMPDB..#Date') IS NULL CREATE TABLE #Date (DateOne DATE)
INSERT INTO #Date VALUES (@StartDate)
WHILE @StartDate < @EndDate
BEGIN
INSERT INTO #Date
SELECT DATEADD (DD, 1, @StartDate) AS Date
SET @StartDate = DATEADD (DD, 1, @StartDate)
END
SELECT * FROM #Date