SQL精华收集
order by 的数值型灵活使用
select * from table_a where id=p_id order by decode(函数,'asc',1,'desc',-1)*jsny;
控制试图的访问时间:
6.create view ...
as
select ... from where exists(select x from dual where sysdate>=8:00am and sysdate<=5:00pm)
妙用decode实现排序
select * from tabname
order by decode(mode,'FIFO',1,-1)*to_char(rq,'yyyymmddhh24miss');
select * from tabname
order by decode(mode,'FIFO',rq-sysdate, sysdate-rq)
找出某个时期内工作日数:
select count(*)
from ( select rownum-1 rnum
from all_objects
where rownum <= to_date('2002-02-28','yyyy-mm-dd') - to_date('2002-
02-01','yyyy-mm-dd')+1 )
where to_char( to_date('2002-02-01','yyyy-mm-dd')+rnum-1, 'D' ) not
in ( '1', '7' )
我觉得查询重复记录的语句就很经典
select rowid,bdsszd from BADWDJ a where a.rowid != (select max(rowid) from BADWDJ b where a.bdsszd =b.bdsszd)
由它引申的就有很多有用的语句,如昨天回答别人的排序的难题
select id,bdsszd from BADWDJ a where a.id = (select max(id) from BADWDJ b where a.bdsszd =b.bdsszd) order by id
树型结构表的查询:
select ID,PARENT_ID from parent_child
connect by prior id = parent_id
start with id = 1;
1.decode这个函数一定需要会,我觉得sql的灵活很多地方都是通过这个function来体现的,相当于if,很好用。
2.group by,这个东东想想简单,其实好多统计功能是离不开这个操作的。oracle8中扩充了group by rollup和cube的操作。有时候省了你好多功夫的。值得注意的是,当你对事物做过有效的人为归并之后执行group by 往往会更让人心旷神怡。
3.很表竖置的经典写法,也要记住:sum(decode( )) group by ...
注意:需要在一个subquery中确定一个横置判点。
4.树形结构表的遍历写法:select ...from ....
start with ... connect by prior (父子关系表达式)
select * from xxx where decode(:var,null,'0',column1) = decode(:var,null,'0',:var);
816以上的 一些分析函数如 rank() over() and row_number() over()
当然关于 group by rollup/cube使用的人恐怕特别少
如何实现最大匹配的操作?
例如:给定字符串 '1234', 而表中可能有记录项'1','12','123','1234','12345',要选出'
相关文档:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_convert]') and xtype in (N'FN', N'IF', N'TF'))&n ......
转自:http://hong9270503.blog.163.com/blog/static/127292320091611319516/
通过SQL*PLUS我们可以构建友好的输出,满足多样化用户需求。
本例通过简单示例,介绍通过sql*plus输出xls,html两种格式文件.
首先创建两个脚本:
1.main.sql
用以设置环境,调用具体功能脚本
2.功能脚本-ge ......
1.修改列
EXEC sp_rename 'TableName.ColumnName','NewColumName'
2.增加列
ALTER TABLE TableName ADD ColumnName int --Type In Here
3.删除列
ALTER TABLE TableName DROP Column ColumnName ......
对这个进行优化
select n5001 门店,n5002 部门,n5004 小分类,n5019 商品编码,c01d21 商品名称,
nvl(xse,0)-nvl(dzxs,0) 销售,
mle 毛利,
nvl(xl,0)-nvl(dzsl,0) 销量
from
(select n5001,n5002,n5004,n5019,sum(n5011) xse,sum(n5016) mle,sum(n5023) xl
from n50
where to_char(n5010,'yyyymmdd')>='20 ......