我想在我的查詢中的WHERE子句中使用計算的字段值,經過一些研究後,我知道我需要創建派生表。我不知道語法,但是由於我的計算字段使用像一個CASE語句:SQL Server - 如何使用派生表計算字段?
CASE T.IsReassigned
WHEN 1 THEN DATEDIFF(MINUTE,
(SELECT top 1 SXAVWFTaskHistory.CreatedWhenUTC from SXAVWFTaskHistory where TaskID = T.TaskID and StatusID = 7 order by TaskHistoryID desc),
SYSDATETIMEOFFSET())
ELSE
CASE Stat.StatusID
WHEN 1 THEN DATEDIFF(MINUTE,TSK.CreatedWhenUTC, SYSDATETIMEOFFSET()) -- time duration between when task is created(use SXAVWFTask.CreatedWhenUTC) and now
WHEN 2 THEN DATEDIFF(MINUTE,TSK.CreatedWhenUTC, SYSDATETIMEOFFSET()) -- time duration between when task is created(use SXAVWFTask.CreatedWhenUTC) and now
ELSE DATEDIFF(MINUTE,TSK.CreatedWhenUTC, TH.CreatedWhenUTC)
END
END as TaskItemAge,
我想那麼在使用TaskItemAge值where子句類似:
WHERE TaskItemAge > @TaskAgeStart AND TaskItemAge < @TaskAgeEnd
怎麼辦我把這個CASE語句放入一個子選擇中?
** * ** * ** * ** * ** 編輯 ** * ** * ** * * * * 對不起,我還是有點困惑,這將如何工作。這裏是我的查詢較大片段:
SELECT TSK.TaskID, --0
TH.IsLatest,
TH.CreatedWhenUTC as TaskHistoryCreationDate, --10
TS.Name AS STATE,
CASE T.IsReassigned
WHEN 1 THEN DATEDIFF(MINUTE,
(SELECT top 1 SXAVWFTaskHistory.CreatedWhenUTC from SXAVWFTaskHistory where TaskID = T.TaskID and StatusID = 7 order by TaskHistoryID desc),
SYSDATETIMEOFFSET())
ELSE
CASE Stat.StatusID
WHEN 1 THEN DATEDIFF(MINUTE,TSK.CreatedWhenUTC, SYSDATETIMEOFFSET()) -- time duration between when task is created(use SXAVWFTask.CreatedWhenUTC) and now
WHEN 2 THEN DATEDIFF(MINUTE,TSK.CreatedWhenUTC, SYSDATETIMEOFFSET()) -- time duration between when task is created(use SXAVWFTask.CreatedWhenUTC) and now
ELSE DATEDIFF(MINUTE,TSK.CreatedWhenUTC, TH.CreatedWhenUTC)
END
END as TaskItemAge,
ctx.ContextTypeName,
ctx.ContextDescription, --15
TH.TouchedWhenUTC as TaskHistoryModifiedDate
INTO #ii
FROM SXAVWFTask TSK
INNER JOIN SXAVWFTaskHistory TH ON TSK.TaskID = TH.TaskID
INNER JOIN @PagedTemp T on TH.TaskHistoryID = T.TaskHistoryID
Where TaskItemAge > @TaskAgeStart AND TaskItemAge < @TaskAgeEnd
A * Derived Table *是由SELECT語句生成(即,派生自)的任何一組行。在SQL Server派生表中,也可用於查詢的項目包括1)子查詢,2)CTE和3)視圖。 – RBarryYoung