SQL 笔记

发布于:2025-09-11 ⋅ 阅读:(20) ⋅ 点赞:(0)

create table t1(id int,name varchar2(10));
insert into t1 values(1,'aaa');
insert into t1 values(2,'bbb');
insert into t1 values(3,'ccc');
insert into t1 values(4,'ddd');
insert into t1 values(5,'eee');
commit;

create table t1_a as select * from t1 where 1=2;
create table t1_b as select * from t1 where 1=2;
无条件多表插入:
insert all into t1_a into t1_b select * from t1;
有条件多表插入:
insert all when id<3 then into t1_a else into t1_b select * from t1;

优先插入:
insert first when id<3 then into t1_a when id>1 then into t1_b select * from t1;


旋转插入:行列转换
create table sales(id number,name varchar2(10),q1 number,q2 number,q3 number,q4 number);
insert into sales values(1,'apple',1000,2000,3000,4000);
insert into sales values(2,'orange',2000,2000,4000,4000);
insert into sales values(3,'grape',1500,2000,3600,4000);
insert into sales values(4,'banana',1900,2000,3900,4000);
commit;

create table sales_info(id number,name varchar2(10),quarter varchar2(5),smount number);

insert all 
into sales_info values(id,name,'q1',q1)
into sales_info values(id,name,'q2',q2)
into sales_info values(id,name,'q3',q3)
into sales_info values(id,name,'q4',q4)
select id,name,q1,q2,q3,q4 from sales;

列转行:
select * from ((select id,name,smount,quarter from sales_info) pivot(sum(smount) for quarter in ('q1' as q1,'q2' as q2,'q3' as q3,'q4' as q4)))

SELECT [非聚合列]
FROM [源表或子查询]
PIVOT (
  聚合函数(待聚合列)  -- 对数据进行聚合(如SUM、COUNT、AVG等)
  FOR [行转列的基准列]  -- 指定哪一列的取值将转换为新列
  IN (值1 AS 列名1, 值2 AS 列名2, ...)  -- 明确要转换为列的具体值及对应列名
);


with 子句:
WITH aaaa AS (SELECT * FROM "SYSIBM".SYSDUMMY1 s), bbbb AS (SELECT * FROM aaaa) SELECT * FROM bbbb;

分页查询公式:
分页查询起始行=(页码 - 1)*每页长度 + 1
分页查询中止行= 页码*每页长度 

跳过前5行,取后面5行:(12C才有的功能)
select * from jk order by sn offset 5 rows fetch next 5 rows only;

前10%的记录:
select * from jk order by sal desc fetch first 10 percent rows only;

如果有并行的值,也要显示出来(即使超出了实际规定的百分比)
select * from jk order by sal desc fetch first 10 percent rows with ties;


如果不喜欢自己换算时间,则用timestamp with local time zone 会将用户输入的时间转换为数据库服务器所在时区的时间
如果喜欢保存原本的时区信息,则用timestamp with time zone

create table meeting(name varchar2(10),
time1 timestame,
time2 timestamp with time zone,
time3 timestame with local time zone);


 


网站公告

今日签到

点亮在社区的每一天
去签到