学以致用,欢迎转载,更多联系QQ:289325414
自己的一些常用心得写法
目录
七、 统计SQL,函数内加判断 count() 、sum() 、count() 去重用法
一、数据条件过滤
select a from table where a=b 字段a 不要使用函数去进行转换
to_date,to_char,substr ,会极大加慢查询效率
二、除数为零
除数为零,报错避免写法 select decode(b,0,0,a/b) from dual;
三、得出一周连续的日期
SELECT to_char (to_date('2018-01-24')- LEVEL + 1, 'yyyy-mm-dd') today FROM
DUAL connect BY LEVEL <= 7;
四、trunc
trunc 函数,trunc(sysdate,'DD') 得出yyyy-mm-dd标准日期,去掉时分秒,trunc(sysdate,'MM') 得出某一个在这个月的第一天
五、instr()
instr()函数。等同于like ‘%xxx%’
select * from test t
where instr(t.xxx,'xx')>0
or 方法用法代替
select * from test t
where instr(‘123,321’,t.xxx)>0
六、判断字段为空写法
select*from tab_i t where 1=nvl(t.col_x,1);
不为空写法
select*from tab_i t where 1!=nvl(t.col_x,1);
七、 统计SQL,函数内加判断 count() 、sum() 、count() 去重用法
with t1 as (
select '张三' as name , '语文' as calls , '89' as scare from dual
union all
select '张三' as name , '语文' as calls , '88' as scare from dual
union all
select '张三' as name , '数学' as calls , null as scare from dual
union all
select '张三' as name , '英语' as calls , '68' as scare from dual
union all
select '李四' as name , '语文' as calls , '99' as scare from dual
union all
select '李四' as name , '数学' as calls , '66' as scare from dual
union all
select '李四' as name , '英语' as calls , null as scare from dual
)
select name,count(case when scare is not null then calls else null end) as 分数不为空的课程有几门count写法
,sum( case when scare is not null then 1 else 0 end) as 分数不为空的课程有几门sum写法
,count(distinct case when scare is not null then calls else null end) as 分数不为空的课程有几门去重版
from t1 group by name;
八、更新方法:
1、A数据更新B表数据
update P_H_MME_QUALITY_CHECK A set A.LOWSINR0=
(SELECT B.LOWSINR0 FROM P_H_RST_XDR_COVERS B WHERE A.HOUR_ID=B.HOUR_ID
AND A.MSISDN=B.MSISDN AND A.VERSION_DATE=B.VERSION_DATE)
COMMIT;
九、用户解锁
alter user username account unlock;(username 指的是数据库用户名)
十、表解锁
SELECT 'alter system kill session ''' || c.sid || '' || ',' || c.serial# ||''';'
, a.object_id, a.session_id, b.object_name, c.*
FROM v$locked_object a, dba_objects b, v$session c
WHERE a.object_id = b.object_id
AND a.SESSION_ID = c.sid(+)
AND B.OBJECT_NAME = 'test_table'
ORDER BY logon_time;
十一、查找表名
select table_name from user_tables where table_name like '%CJW%';
十二、查询分区有无数据,得出有数据的分区
1、analyze table test_table compute statistics for table for all indexes for all indexed columns;
第一步 通常是在该分区数据入库完成后,调用的,调用分析分区的数据,分析后 表 (USER_TAB_PARTITIONS)的分区信息会补充完整
2、SELECT substr(PARTITION_NAME,2) yyyymmdd FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME = 'test_table'
AND SAMPLE_SIZE IS NOT NULL
第二步是实时查询的,能非常快速得出有数据的分区是哪些