继续发帖求一个SQL语句的编写或优化
订单信息表t1:order_id(订单号) add_time(下单时间) tourist_id(客户信息)
客户信息表t2: tourist_id(客户信息) tel1 tel2 tel3 tel4(四个电话或手机号码)
呼出信息表t3: tel(呼出电话) calltime(呼出时间)
其中t1中tourist_id关联到t2中tourist_id,t3中的tel可能为t2中的任一个
查询过程:根据order_id找到4个号码,根据4个号码找到对应到该order_id的呼出时间,然后用calltime-add_time得到呼出时间差
查询结果: 订单号 下单时间 第一次呼出时间差 第二次呼出时间差 第三次呼出时间差
望高手解答!
或者将下面的SQL语句优化下,昨天SQLCenter回复的一个SQL语句我今天执行了一下,发现效率非常低,几分钟都没有结果,被我取消了,而且我才导了不到2个月的数据,大概70W条记录,希望能优化下,急盼回复!
附
with cte as( select id=row_number()over(partition by t1.order_id order by t3.calltime), t1.order_id, t1.add_time, diff=datediff(second, t1.add_time, t3.calltime) from t1 join t2 on t1.tourist_id=t2.tourist_id join t3 on t2.tel1=t3.tel or t2.tel2=t3.tel or t2.tel3=t3.tel or t2.tel4=t3.tel)select order_id, [1] = max(case id when 1 then diff end), [2] = max(case id when 2 then diff end), [3] = max(case id when 3 then diff end)from cte group by order_id
1 2 3diff1 null nullnull diff2 nullnull null diff3
[解决办法]
客户信息表t2: tourist_id(客户信息) tel1 tel2 tel3 tel4(四个电话或手机号码)
-----------
速度瓶颈应该在这里,如果有一个这样的表:
t2_tel:
id tourist_id tel1 1 tel12 1 tel23 1 tel34 1 tel45 2 tel16 2 tel27 2 tel38 3 tel1。。。
[解决办法]
with r as (
select a.order_id
,a.add_time
,c.calltime
from t1 a inner join
t2 b on a.tourist_id=b.tourist_id cross apply
(select top 3 calltime from t3 where tel=b.tel1 and calltime>a.add_time/*锁定add_time后的电话时间*/ order by calltime) c
union all
select a.order_id
,a.add_time
,c.calltime
from t1 a inner join
t2 b on a.tourist_id=b.tourist_id cross apply
(select top 3 calltime from t3 where tel=b.tel2 and calltime>a.add_time/*锁定add_time后的电话时间*/ order by calltime) c
union all
select a.order_id
,a.add_time
,c.calltime
from t1 a inner join
t2 b on a.tourist_id=b.tourist_id cross apply
(select top 3 calltime from t3 where tel=b.tel3 and calltime>a.add_time/*锁定add_time后的电话时间*/ order by calltime) c
union all
select a.order_id
,a.add_time
,c.calltime
from t1 a inner join
t2 b on a.tourist_id=b.tourist_id cross apply
(select top 3 calltime from t3 where tel=b.tel4 and calltime>a.add_time/*锁定add_time后的电话时间*/ order by calltime) c
)
,
r1 as (
select order_id
,secondAfterAdd=datediff(second, add_time,calltime)
,id=row_number() over(partition by order_id order by calltime)
from r
)
select order_id
,[call_1]=max(case when id=1 then secondAfterAdd end)
,[call_2]=max(case when id=2 then secondAfterAdd end)
,[call_3]=max(case when id=3 then secondAfterAdd end)
from r1
where id<=3
group by order_id
楼主可否再测试下这个
建议 索引情况
t1 order_id 主键
t2 tourist_id 主键
t3 做个 tel,calltime 的联合索引
这个是老系统的 BI 应用吧,数据的数量级应该不大