示例:SQL查找积分最高的用户的id,名字,以及他的总积分是多少(可能有多个),查询结果按照id升序排序
查询结果如下:
有的时候衔接的表需要重复引用,with as可以大大提高语句的可读性,精简语句。但是缺点也很明显,不能重复调用。
with T as (
select user_id,sum(case when type='add' then grade_num
else -grade_num end) as grade_sum
from grade_info
group by user_id)
select T.user_id as id,user.name,T.grade_sum
from T join user on T.user_id=user.id
where T.grade_sum=(select max(grade_sum) from T)
order by id