怎么优化下面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 17:02:09 浏览: 76
可以考虑使用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语句更加可读性强,更加易于维护。
相关问题
select i.id, i.name, i.group_id, i.max_people, i.create_time, u.nick_name, w.shrimp, gb.total, gpo.order_total, gpo.rake_total, gpo.shell_total, gpo.consume_total from im_group_information i left join im_group g on g.group_id = i.group_id and g.admin=2 left join (select group_id, count(group_id) total from im_group where is_delete=0 group by group_id) gb on gb.group_id = i.group_id left join (select bid, count(bid) order_total, sum(rake) rake_total, sum(price) shell_total, count(distinct uid) consume_total from g_prop_order where is_delete=0 group by bid) gpo on gpo.bid = g.u_id left join u_user u on u.id = g.u_id left join u_wallet w on w.id = g.u_id left join (select uid, count(distinct uid) offline_total from u_online_log group by uid) l on g.u_id = l.uid where i.is_delete = 0;怎么查到im_group_information群组表中七天内登陆过的用户数量
可以使用子查询结合条件判断的方式来查询七天内登陆过的用户数量,具体实现如下:
```
SELECT COUNT(DISTINCT l.uid) AS login_total
FROM im_group_information i
LEFT JOIN im_group g ON g.group_id = i.group_id AND g.admin = 2
LEFT JOIN u_user u ON u.id = g.u_id
LEFT JOIN u_online_log l ON g.u_id = l.uid
WHERE i.is_delete = 0
AND l.login_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)
```
这里使用了 `COUNT(DISTINCT l.uid)` 来统计七天内登陆过的用户数量,同时在 `WHERE` 子句中加入条件 `l.login_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)` 来筛选出七天内登陆过的用户。
SELECT * FROM d_bd_bideval AS a INNER JOIN d_bd_bid AS bid ON a.bidid = bid.bidid INNER JOIN d_bd_bidevalexpertdtl AS b ON a.bidevalid = b.bidevalid WHERE ( b.expertmajortype = 'ExpertMajorType_001' OR bid.scoreMethod = 'unEval' ) AND ( a.bidEvalNo LIKE '%BED20230315000002%' ) 我要对这一段sql语句进行去重
对于这段SQL语句,如果你想去重复数据,可以使用DISTINCT关键字来实现。修改后的SQL语句如下:
```
SELECT DISTINCT a.*, bid.*, b.*
FROM d_bd_bideval AS a
INNER JOIN d_bd_bid AS bid ON a.bidid = bid.bidid
INNER JOIN d_bd_bidevalexpertdtl AS b ON a.bidevalid = b.bidevalid
WHERE (b.expertmajortype = 'ExpertMajorType_001' OR bid.scoreMethod = 'unEval')
AND (a.bidEvalNo LIKE '%BED20230315000002%')
```
这样就可以保证查询结果中没有重复的数据了。
阅读全文