-这是我当前的代码,它使我能够查看过去一周内提交的所有工作订单,并让我知道是否有相同的工作订单在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
-但是,现在我想获取第一个变量getdate / adddate。要检查1年前,+ /-15天。因此基本上是1年零15天而不是6个月。
答案 0 :(得分:0)
过去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
1年
SELECT ...
FROM ...
WHERE wo_requestDate BETWEEN DATEADD(year, -1, GETDATE()) AND GETDATE()
AND...;
15天
SELECT ...
FROM ...
WHERE wo_requestDate BETWEEN DATEADD(day, -15, GETDATE()) AND GETDATE()
AND...;
DATEADD()
year
quarter
month
dayofyear
day
week
weekday
hour
minute
second
millisecond
查看更多here。
。
答案 1 :(得分:0)
要消除datetime的时间部分问题,请执行以下操作:
CAST(GETDATE() AS DATE
查找一年前的日期:
SELECT DATEADD(YEAR, -1, CAST(GETDATE() AS DATE));
从那里减去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)))
我更喜欢>=
和<
而不是BETWEEN
,尤其是在日期方面,只是为了避免时间部分含糊不清,因此,如果需要在最后一个参数上加上16天,您希望范围包括第15天。