我有一个MSSQL 2000数据库,其中包含我需要执行查询的表。 它有一个'STEP'列和列'DATE1','DATE2'......'DATE7'。当一个特定的脚本运行时,它会更新'DATE $ step'列并将'STEP'递增一个(必要时包裹)。
我正在尝试创建一个查询,该查询返回最后一个日期的行,例如如果'STEP'= 4,'DATE3'比X天还要早,但我对如何进行此查询感到有些困惑。
答案 0 :(得分:3)
这样的东西?
SELECT
[DateColumn]=CASE STEP WHEN 1 THEN DATE1
WHEN 2 THEN DATE2
WHEN 3 THEN DATE3
ELSE DATE4 END
FROM <Table>
答案 1 :(得分:1)
select Step, [Date]
from
(select
Step,
case Step
when 1 then Date1
when 2 then Date2
when 3 then Date3
when 4 then Date4
when 5 then Date5
when 6 then Date6
when 7 then Date7
end as [Date]
from YourTable) as T
where datediff(d, T.[Date], getdate()) > @XDays
答案 2 :(得分:1)
Select MyTable.* from MyTable INNER JOIN
(Select tableID, CASE STEP
WHEN 7 THEN DATE6 -- The STEP column increments are done
WHEN 6 THEN DATE5 -- *after* updating the date, therefore
WHEN 5 THEN DATE4 -- the last update date is in Date[STEP-1]
WHEN 4 THEN DATE3
WHEN 3 THEN DATE2
WHEN 2 THEN DATE1
WHEN 1 THEN DATE7 -- Rollover (special case)
END AS LastDate
From MyTable
-- DATEDIFF Returns the count (signed integer) of the specified
-- datepart boundaries crossed. I therefore use seconds
-- to get predicable results regardless of execution time.
-- (86400 seconds in a day)
WHERE DATEDIFF('s',LastDate,getdate()) >
(86400 * @DaysParameter)) as dateResult
ON MyTable.tableID = dateResult.tableID