【发布时间】:2017-03-21 13:10:04
【问题描述】:
我在#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 语句根本不会给出想要的结果,但只有很少的行被更新了值。我不知道为什么?!
def 包含已服务多次的所有订单的列表。
编辑:根据@sqlzim 的回复,我更改了查询。他的回复也给出了同样的答案。
【问题讨论】:
-
左对齐 SQL...很难阅读...
-
请添加一些示例表数据和预期结果 - 以及格式化文本。同时向我们展示您当前的查询尝试
标签: sql cross-apply