[英]Using COUNT(*) inside CASE statement in SQL Server
是否可以在T-SQL的case語句中使用count(*)? 我正在嘗試更新表中的記錄,但我希望有2種情況。
第一種情況應在EndDate小於StartDate時進行更新,第二種情況應僅在我具有特定EmployeeId的確切記錄時進行更新。
update ep
set ep.EndDate = case when t.EndDate < t.StartDate then t.EndDate3
case when COUNT(*) = 1 then null
end ,ep.ModifiedBy = 'PCA', ep.ModifiedDate = getdate()
from dbo.EmployeeProductivity ep inner join cteT1 t
on ep.Id = t.Id
where t.EndDate < t.StartDate
or t.EndDate is null
我正在嘗試類似的操作,但是出現如下錯誤:
an expression of non boolean type specified in a context where a condition is expected
這是完整的腳本:
use ws3;
select distinct (EmployeeId) as EmployeeId
into #Emps
from [dbo].[EmployeeProductivity]
where EndDate < StartDate
or EndDate is null;
with cteProdRates as
(
select ep.[ID]
,ep.[EmployeeId]
,ep.[FormatId]
,ep.[StartDate]
,ep.[EndDate]
,dateadd(dd, -1, lag(startdate) over (partition by ep.EmployeeId, FormatId order by StartDate desc, Id desc)) as EndDate2
,ep.[Rate]
FROM [dbo].[EmployeeProductivity] ep inner join #Emps e
on ep.EmployeeId = e.EmployeeId
)
,cteT1 as
(
select [ID]
,[EmployeeId]
,[FormatId]
,[StartDate]
,[EndDate]
,case when EndDate2 < StartDate then StartDate else EndDate2 end as EndDate3
,[Rate]
from cteProdRates
)
update ep
set ep.EndDate = case when t.EndDate < t.StartDate then t.EndDate3
case when COUNT(*) = 1 then null
end ,ep.ModifiedBy = 'PCA', ep.ModifiedDate = getdate()
from dbo.EmployeeProductivity ep inner join cteT1 t
on ep.Id = t.Id
where t.EndDate < t.StartDate
or t.EndDate is null
drop table #Emps
因此,對於每個唯一的EmployeeId,我都有多個條目。 每個StartDate必須大於EndDate,並且當使用新StartDate添加新條目時,上一個條目EndDate設置為newEntry.StartDate-1。僅當條目是最后一個條目時,EndDate設置為NULL,這意味着該條目不是關閉了
這就是為什么當我只有一個條目用於特定EmployeeId時需要檢查大小寫,因此我可以將其設置為NULL。
甚至可以比較嗎?或者我缺少什么? 有人對此有經驗嗎?
您不能在update
使用count(*)
。 這與case
表達式無關。
也許這就是您想要的:
update ep
set ep.EndDate = (case when t.EndDate < t.StartDate then t.EndDate3
when cnt = 1 then null
end),
ep.ModifiedBy = 'PCA',
ep.ModifiedDate = getdate()
from dbo.EmployeeProductivity ep inner join
(select t.*, count(*) over (partition by id) as cnt
from cteT1 t
where t.EndDate < t.StartDate or t.EndDate is null
) t
on ep.Id = t.Id
當然,正如邏輯上所說的那樣, count()
上的條件是多余的-不管怎么說case
表達式都返回NULL
,所以這個邏輯看起來是等效的:
update ep
set ep.EndDate = (case when t.EndDate < t.StartDate then t.EndDate3
end),
ep.ModifiedBy = 'PCA',
ep.ModifiedDate = getdate()
from dbo.EmployeeProductivity ep inner join
from cteT1 t
on ep.Id = t.Id
where t.EndDate < t.StartDate or t.EndDate is null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.