本文已参与「新人创作礼」活动,一起开启掘金创作之路。
13.如果用了窗口函数,就不能在这个查询中使用where!
需要再嵌套一层再使用where,否则会出现unknown cloumn
select distinct t.seat_id from(
(select seat_id,
sum(free) over(rows 1 preceding ) as smkk
from cinema
)
union all
(select seat_id,sum(free) over(rows between 0 preceding and 1 following ) as smkk #可以做命名
from cinema
)
)t
where smkk>1 #但是嵌套必须在外面
order by t.seat_id
但是,与上面的写法不同,你如果
between 1 preceding and 1 following
可能会导致整个表作为循环状态进行统计
14.inner join 是直接做笛卡尔积的交!
15.逻辑比较:
select
round(min(sqrt(power(p1.x-p2.x,2) + power(p1.y-p2.y,2))),2) shortest
from point2d p1 ,point2d p2
where p1.x<>p2.x and p1.y<>p2.y
# select round(min(sqrt(power(p1.x-p2.x,2) + power(p1.y-p2.y,2))),2) shortest
# from point2d p1, point2d p2
# where (p1.x, p1.y) <> (p2.x,p2.y)
这两个地方不同:where--->不同的做法会导致不同的含义
!!!!
16.表别名
select name from salesperson
where sales_id not in
(
select
sales_id
from company c right join orders o on o.com_id=c.com_id
where c.name='RED') #类似这种in的情况就不需要别名了,好像需要列名的时候就是在1.from后加括号:子查询 2.join连接
17.多个参数的窗口函数用 逗号分割
avg(t1.amount) over(partition by t1.department_id,t1.pay_date) dp_s,
18.distinct 在最开始的位置就还可以实现显示的所有行去重
distinct t2.pay_month,
t2.department_id,
case when dp_s>m_s then 'higher'
when dp_s<m_s then 'lower'
when dp_s=m_s then 'same'
end as comparison
18.行转列----->怎么做?
select
max(if (continent='America',name,null)) America,
max(if(continent='Asia',name,null)) Asia,
max(if(continent='Europe',name,null)) Europe
from
(select *,
row_number() over (partition by continent order by name ) rk
from student) t1
group by rk
代码运行逻辑
:
1.得到表t1---->得到的是一个所有正常数据+按照洲group的各自排名
2.按照group by 排名
3.插入原理:id都是1的插入第一行,id都是2的第二行,如果数量有空缺,补入null
4.max的原理是和null比较,如果有名字,则返回名字,否则返回null,如果没有null是这样的 (#还要看一下
用IF或CASE WHEN将行转列,过程会产生大量NULL,用聚合如MAX/MIN,均可去除NULL