怎么优化下面SQL: select distinct bid from ( select row_number() over(order by bid,start_date) as num,bid,start_date,end_date from t1 )a inner join ( select row_number() over(order by bid,start_date) as num,bid,start_date,end_date from t1 )b on a.bid = b.bid where a.num = b.num+1
时间: 2023-12-29 14:02:09 浏览: 68
SQL如何优化
可以考虑使用CTE(公共表表达式)来优化该SQL语句。具体做法如下:
```
WITH cte AS (
SELECT ROW_NUMBER() OVER (ORDER BY bid, start_date) AS num, bid, start_date, end_date
FROM t1
)
SELECT DISTINCT a.bid
FROM cte a
INNER JOIN cte b ON a.bid = b.bid AND a.num = b.num + 1
```
使用公共表表达式的好处是可以避免重复计算,使得SQL语句更加简洁和易于理解。在这个例子中,我们只需要计算一次ROW_NUMBER()函数,然后在CTE中引用它即可。同时,使用WITH语句也可以使得SQL语句更加可读性强,更加易于维护。
阅读全文