[英]Looking for a getdate/dateadd statement to do 1 year and +/- 15 days
-- This is my current code which will allow for me to see all our work orders that have been submitted within the past week, and lets me know if any of the same work orders have appear 6 months ago. -这是我当前的代码,它使我可以查看过去一周内提交的所有工作订单,并让我知道是否有相同的工作订单出现在6个月前。
SELECT
A.tagnumber,
count(*) AS CountTotal
FROM
v_workorder A
WHERE
--Date range Within Today and 6 months ago
wo_requestDate BETWEEN DATEADD(month, -6, GETDATE()) AND GETDATE()
AND
EXISTS
( -- Date range Within Today and 7 days ago
select
tagnumber
FROM
v_workorder
WHERE
wo_requestDate BETWEEN DATEADD(DAY,-7,GETDATE()) AND GETDATE()
)
AND
A.wc_description = 'Corrective'
AND
A.itemtype_name = 'Building'
GROUP BY A.tagnumber
ORDER BY CountTotal DESC
--However, Now I would like for my first variable of the getdate/adddate. -但是,现在我要获取getdate / adddate的第一个变量。 To check back 1 year ago, +/- 15 days.
要检查1年前,+ /-15天。 So essentially 1 year and 15 days back instead of 6 months.
因此基本上是1年15天,而不是6个月。
For past 1 year +/- 15 Days 过去1年+/- 15天
SELECT A.tagnumber, count(*) AS CountTotal
FROM v_workorder A
WHERE wo_requestDate BETWEEN DATEADD(day, -15, DATEADD(year, -1, GETDATE())) AND DATEADD(day, 15, DATEADD(year, -1, GETDATE()))
AND
EXISTS ( select tagnumber FROM v_workorder WHERE wo_requestDate BETWEEN DATEADD(DAY,-7,GETDATE()) AND GETDATE() )
AND
A.wc_description = 'Corrective' AND A.itemtype_name = 'Building'
GROUP BY A.tagnumber
ORDER BY CountTotal DESC
For 1 year 一年
SELECT ...
FROM ...
WHERE wo_requestDate BETWEEN DATEADD(year, -1, GETDATE()) AND GETDATE()
AND...;
For 15 Days 15天
SELECT ...
FROM ...
WHERE wo_requestDate BETWEEN DATEADD(day, -15, GETDATE()) AND GETDATE()
AND...;
Other possible options of DATEADD()
DATEADD()
其他可能选项
year
quarter
month
dayofyear
day
week
weekday
hour
minute
second
millisecond
. 。
To eliminate issues with the time component of datetime: 要消除datetime的时间部分的问题,请执行以下操作:
CAST(GETDATE() AS DATE
Find the date from a year ago: 查找一年前的日期:
SELECT DATEADD(YEAR, -1, CAST(GETDATE() AS DATE));
From there, subtract 15 days and add 15 days in your end points. 从那里减去15天,然后在终点增加15天。
...
WHERE
wo_requestDate >= DATEADD(DAY, -15, DATEADD(YEAR, -1, CAST(GETDATE() AS DATE)))
AND
wo_requestDate < DATEADD(DAY, 15, DATEADD(YEAR, -1, CAST(GETDATE() AS DATE)))
I prefer >=
and <
to BETWEEN
, especially with dates, just to avoid any ambiguity with the time component, so you may want to add 16 days to the last parameter if you want the range to include the 15th day out. 我更喜欢
>=
和<
而不是BETWEEN
,尤其是对于日期,只是为了避免与时间成分有任何歧义,因此,如果希望范围包括第15天,则可能需要在最后一个参数中添加16天。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.