[英]Update with cross apply in SQL SERVER
我在#def 中有一個這樣的表:
#def table我只想計算當前期間“201702”的每個服務訂單之間的天數。 Reservice = 0 表示之前沒有維修過。 重新服務的次數隨着每次重新服務而增加。
select
s1.period,
,s1.company
,s1.prod
,s1.id1
,S1.id2
,s1.serv_date
,t.last_servdate
,datediff(dd, ISNULL(T.last_servdate, s1.[serv_Date]),s1.serv_date)AS [Days Since last] from #def s1
Outer apply(
select
top 1 serv_date as last_servdate from #def s2
where s1.prod=s2.prod and s1.id1 =s2.id1
and s1.id2=s2.id2 and s1.company =s2.company
and s2.reservice = s1.reservice-1 and s1.company =’abc’
and s2.company =’abc’)T
where s1.company_code =’abc’ and s1.period ='201702'
update s1
set days_btwn_service = datediff(dd, ISNULL(T.last_servdate,s1.serv_Date]),s1.serv_date) from #def s1
Outer apply(
select top 1 serv_date as last_servdate from #def s2
where s1.prod=s2.prod
and s1.id1 =s2.id1
and s1.id2=s2.id2
and s1.company =s2.company
and s2.reservice = s1.reservice-1
and s1.company =’abc’
and s2.company =’abc’
)T where s1.company_code =’abc’ and s1.period ='201702'
上面的SELECT
查詢給了我想要的結果。 奇怪的是,使用具有相同查詢的UPDATE
語句根本不會給出所需的結果,但只有很少的行用值更新。 我不知道為什么?!
編輯:根據@sqlzim 的回復,我更改了查詢。 他的回答也給出了同樣的答案。
這看起來像 sql-server,所以這個答案是針對 sql-server 的。
我不明白為什么你會從這些查詢中得到兩個不同的結果,但是如果你用你的select
語句得到了正確的結果,你可以把它放在一個公共表表達式中並使用cte
update
。
serv_date
空嗎? 如果不是,則T.serv_date
不能為空,除非您使用outer apply()
而不是cross apply()
。
;with cte as (
select
s1.ord_id
, s1.period
, s1.company
, s1.prod
, s1.id1
, S1.id2
, s1.serv_date
, s1.days_btwn_service
, t.last_servdate
, datediff(day,isnull(T.last_servdate,s1.[serv_Date]),s1.serv_date) as [Days_Since_Last]
from #def s1
cross apply (
select top 1 serv_date as last_servdate
from #def s2
where s1.prod = s2.prod
and s1.id1 = s2.id1
and s1.id2 = s2.id2
and s1.company = s2.company
and s2.reservice = s1.reservice - 1
) T
where s1.company_code = 'abc'
and s1.period = '201702'
)
--select * from cte;
update cte
set days_btwn_service = [Days_Since_Last];
/* This will update the underlying table #def */
/* -- Alternate version
update d
set d.days_btwn_service = cte.[Days_Since_Last]
from #def d join cte on cte.ord_id=d.ord_id
--*/
檢查select
的結果,如果它們正確,則運行update
而不是select
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.