我的表格中的条目将包含这样的数据日期:
Date Value
4-20-2014 45
4-21-2014 15
4-22-2014 35
...
4-30-2014 109
我将在每个星期日执行我的存储过程,这意味着我希望从上周日到昨天(星期六)获得Date
行。
我有以下查询,从上周日到上周六,我认为这是错误的,所以我将其修改如下:
INSERT INTO [database].[dbo].[table]
SELECT (WEEKENDING DATE) AS [Date], SUM([ORDERS]) AS Orders, SUM([B ORDERS]) AS bOrders, SUM([RESULT]) AS Results
FROM [database].[dbo].[origtable]
WHERE
[Date] >= "PREVIOUS SUNDAY DATE"
AND
[Date] <= "SATURDAY DATE (YESTERDAY)"
我想通过以下方式获得一些帮助:
[Date] >= "PREVIOUS SUNDAY DATE"
AND
[Date] <= "SATURDAY DATE (YESTERDAY)"
因此,如果我在5/4/2014
上运行SP,则会在星期日(4/27/2014
)到星期六(5/3/2014
)之间抓取
这会起作用吗?
INSERT INTO [Database].[dbo].[table]
SELECT
CONVERT(VARCHAR(10), GETDATE(), 101) AS [Date],
SUM([EMR ORDERS]) AS LastWeekEMROrders,
SUM([ACCESSIONED LAB ORDERS]) AS LastWeekAccLabOrders,
SUM([LAB_RESULT]) AS LastWeekLabResults
FROM [database].[dbo].[origtable]
WHERE
[Date] >= DATEADD(day, -((DATEPART(dw, GETDATE()) + @@DATEFIRST) % 7) - 6,
DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)) --PREVIOUS SUNDAY
AND
[Date] <= DATEADD(day, -(DATEPART(dw, GETDATE()) + @@DATEFIRST) % 7,
DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)) --PREVIOUS SATURDAY
如果我有以下查询并在2014年5月4日执行它:
set @startdate = DATEADD(wk, DATEDIFF(wk, 0, getdate()), -2) --for sunday
set @enddate = DATEADD(wk, -1, DATEADD(wk, DATEDIFF(wk, 0,getdate()), -1))-- for saturday
周日和周六的约会对象是什么?
答案 0 :(得分:2)
尝试以下修改过的查询:
修改强>: 该查询已进一步修改为不使用DATEFROMPARTS。
INSERT INTO [Database].[dbo].[table]
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [Date], SUM([EMR ORDERS]) AS LastWeekEMROrders, SUM([ACCESSIONED LAB ORDERS]) AS LastWeekAccLabOrders, SUM([LAB_RESULT]) AS LastWeekLabResults
FROM [database].[dbo].[origtable]
WHERE
[Date] >= DATEADD(d, -8, DATEADD(dd, DATEDIFF(dd,0, current_timestamp), 0)) --PREVIOUS SUNDAY
AND
[Date] <= DATEADD(d, -1, DATEADD(dd, DATEDIFF(dd,0, current_timestamp), 0)) --PREVIOUS SATURDAY;
<强>参考强>:
Date and Time Data Types and Functions (Transact-SQL) on TechNet