各种业务场景下的sql语句

it2023-05-16  74

目录

1.mysql

1.1按表中最小的id去除其他重复数据

1.2将a表数据添加到b表(如果b表已经存在数据则不添加)

1.3联表更新(将a表数据与b表数据关联进行更新b表字段)

1.4将字符类型的数据按整型的顺序来进行排序

1.5选取第8条开始的连续6条数据

 

2.Oracle

2.1按出生日期计算当前年龄

2.2两表关联,重复数据只取第一条

2.3用字符串类型年薪的上下限换算成月薪


1.mysql

1.1按表中最小的id去除其他重复数据

delete from `fh_pc_company` where id not in (select a.id from (SELECT min(id) id,name FROM `fh_pc_company` group by name)a)

1.2将a表数据添加到b表(如果b表已经存在数据则不添加)

tableB中的字段是(id,name,tb_id,tb_name),tableA中的字段是(id,name)

其中tableB中的tb_name字段代表从哪个表插进来,tb_id代表插进来的数据在原表中的id

insert into tableB(name,tb_id,tb_name) select a.name,a.id,"tableA" from tableA a where not EXISTS(select id from tableB where tb_id = a.id and tb_name = 'tableA')

1.3联表更新(将a表数据与b表数据关联进行更新b表字段)

update tableB b,tableA a set b.name=a.name where b.id=a.id

1.4将字符类型的数据按整型的顺序来进行排序

将Records中的recordsNum字段按数字类型进行排序,如003,002,001,在排序时会当成3,2,1来排序

select * from Records order by recordsNum+0 asc;

1.5选取第8条开始的连续6条数据

select * from tableA limit 7,6

 

2.Oracle

2.1按出生日期计算当前年龄

select TRUNC((to_char(sysdate, 'yyyyMMdd') - to_char(a.birthday, 'yyyyMMdd')) /10000) as age from tableA a

2.2两表关联,重复数据只取第一条

a表、b表两表关联,关联出来的结果中,a和b是一对多的关系,而我们只需要其中一条(按某字段来筛选) 

如a,b表数据如下:

执行sql后的需要的结果:

select a.name,t.company from a left join (select b.company,b.person_id from (select b. *,(row_number() over(partition by company order by orderId desc)) su from b) e where su = 1) t on a.id = t.person_id;

2.3用字符串类型年薪的上下限换算成月薪

select ((position.CCE329+0)+(position.CCE330+0))/24 as money from tableA

 

最新回复(0)