求优化sqlserver语句,使它查询效率提高。(要求:分组查询每组最新的一条数据,数据量非常大,几十万)

我的sql :
select a.* from (
SELECT
row_number() over(partition by t.tunnel_name order by t.CreationDate desc) rn,
t.Id,
t.CreationDate,
t.LastUpdate,
t.tunnel_name,
t.SDMC,
t.DT,
t.DZSC1,
t.DZSC2,
t.DZSC3
FROM
dbo.tunnel_online_monitoring AS t
, dbo.Threshold_ElectronicPool AS i) a where a.rn=1

关于题主的SQL语句提高效率的问题,请留意一下几点

1) 输出的字段列表里只有来自表“dbo.tunnel_online_monitoring ”里的字段信息,没有任何来字段取自表“dbo.Threshold_ElectronicPool”,而且语句也没为这两张表指定连接条件,因此将表“dbo.Threshold_ElectronicPool”引入语句中就没有任何必要,加入该表只会大大增加系统开销,而无得益,应予以剔除;

2)row_number()函数的系统开销是比较大的,能不用尽量别用它。

如果dbo.tunnel_online_monitoring.Id是唯一的,可以不使用row_number()函数,建议语句修改如下:

select Id,CreationDate,LastUpdate,tunnel_name,
SDMC,DT,DZSC1,DZSC2,DZSC3 from 
tunnel_online_monitoring where id in (
select max(a.id) from dbo.tunnel_online_monitoring a,
(select tunnel_name,max(CreationDate) as CreationDate from 
dbo.tunnel_online_monitoring group by tunnel_name) b 
where a.tunnel_name=b.tunnel_name and a.CreationDate
=b.CreationDate group by b.tunnel_name);

如果dbo.tunnel_online_monitoring.Id是自增ID,那么可以根据ID的大小来判定那条记录是最新的,这样就不需要比对时间字段的先后了,语句可简化如下:

select Id,CreationDate,LastUpdate,tunnel_name,
SDMC,DT,DZSC1,DZSC2,DZSC3 from 
tunnel_online_monitoring where id in (
select max(id) from dbo.tunnel_online_monitoring 
group by tunnel_name);

如果dbo.tunnel_online_monitoring.Id不是唯一的,那就还是得利用回row_number()函数了。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-05-08
请问您最后是怎么解决的呢?
相似回答