Oracle SQL精妙SQL语句讲解

时间:2022-06-09 05:21:30 其他范文 收藏本文 下载本文

Oracle SQL精妙SQL语句讲解(精选6篇)由网友“Yvonne”投稿提供,下面是小编给大家带来关于Oracle SQL精妙SQL语句讲解,一起来看看吧,希望对您有所帮助。

Oracle SQL精妙SQL语句讲解

篇1:Oracle SQL精妙SQL语句讲解

--行列转换 行转列

DROP TABLE t_change_lc;

CREATE TABLE t_change_lc (card_code VARCHAR2(3), q NUMBER, bal NUMBER);

INSERT INTO t_change_lc

SELECT '001' card_code, ROWNUM q, trunc(dbms_random.VALUE * 100) bal FROM dual CONNECT BY ROWNUM <= 4

UNION

SELECT '002' card_code, ROWNUM q, trunc(dbms_random.VALUE * 100) bal FROM dual CONNECT BY ROWNUM <= 4;

SELECT * FROM t_change_lc;

SELECT a.card_code,

SUM(decode(a.q, 1, a.bal, 0)) q1,

SUM(decode(a.q, 2, a.bal, 0)) q2,

SUM(decode(a.q, 3, a.bal, 0)) q3,

SUM(decode(a.q, 4, a.bal, 0)) q4

FROM t_change_lc a

GROUP BY a.card_code

ORDER BY 1;

--行列转换 列转行

DROP TABLE t_change_cl;

CREATE TABLE t_change_cl AS

SELECT a.card_code,

SUM(decode(a.q, 1, a.bal, 0)) q1,

SUM(decode(a.q, 2, a.bal, 0)) q2,

SUM(decode(a.q, 3, a.bal, 0)) q3,

SUM(decode(a.q, 4, a.bal, 0)) q4

FROM t_change_lc a

GROUP BY a.card_code

ORDER BY 1;

SELECT * FROM t_change_cl;

SELECT t.card_code,

t.rn q,

decode(t.rn, 1, t.q1, 2, t.q2, 3, t.q3, 4, t.q4) bal

FROM (SELECT a.*, b.rn

FROM t_change_cl a,

(SELECT ROWNUM rn FROM dual CONNECT BY ROWNUM <= 4) b) t

ORDER BY 1, 2;

--行列转换 行转列 合并

DROP TABLE t_change_lc_comma;

CREATE TABLE t_change_lc_comma AS SELECT card_code,'quarter_'||q AS q FROM t_change_lc;

SELECT * FROM t_change_lc_comma;

SELECT t1.card_code, substr(MAX(sys_connect_by_path(t1.q, ';')), 2) q

FROM (SELECT a.card_code,

a.q,

row_number over(PARTITION BY a.card_code ORDER BY a.q) rn

FROM t_change_lc_comma a) t1

START WITH t1.rn = 1

CONNECT BY t1.card_code = PRIOR t1.card_code

AND t1.rn - 1 = PRIOR t1.rn

GROUP BY t1.card_code;

--行列转换 列转行 分割

DROP TABLE t_change_cl_comma;

CREATE TABLE t_change_cl_comma AS

SELECT t1.card_code, substr(MAX(sys_connect_by_path(t1.q, ';')), 2) q

FROM (SELECT a.card_code,

a.q,

row_number() over(PARTITION BY a.card_code ORDER BY a.q) rn

FROM t_change_lc_comma a) t1

START WITH t1.rn = 1

CONNECT BY t1.card_code = PRIOR t1.card_code

AND t1.rn - 1 = PRIOR t1.rn

GROUP BY t1.card_code;

SELECT * FROM t_change_cl_comma;

SELECT t.card_code,

substr(t.q,

instr(';' || t.q, ';', 1, rn),

instr(t.q || ';', ';', 1, rn) - instr(';' || t.q, ';', 1, rn)) q

FROM (SELECT a.card_code, a.q, b.rn

FROM t_change_cl_comma a,

(SELECT ROWNUM rn FROM dual CONNECT BY ROWNUM <= 100) b

WHERE instr(';' || a.q, ';', 1, rn) > 0) t

ORDER BY 1, 2;

-- 实现一条记录根据条件多表插入

DROP TABLE t_ia_src;

CREATE TABLE t_ia_src AS SELECT 'a'||ROWNUM c1, 'b'||ROWNUM c2 FROM dual CONNECT BY ROWNUM<=5;

DROP TABLE t_ia_dest_1;

CREATE TABLE t_ia_dest_1(flag VARCHAR2(10) , c VARCHAR2(10));

DROP TABLE t_ia_dest_2;

CREATE TABLE t_ia_dest_2(flag VARCHAR2(10) , c VARCHAR2(10));

DROP TABLE t_ia_dest_3;

CREATE TABLE t_ia_dest_3(flag VARCHAR2(10) , c VARCHAR2(10));

SELECT * FROM t_ia_src;

SELECT * FROM t_ia_dest_1;

SELECT * FROM t_ia_dest_2;

SELECT * FROM t_ia_dest_3;

INSERT ALL

WHEN (c1 IN ('a1','a3')) THEN

INTO t_ia_dest_1(flag,c) VALUES(flag1,c2)

WHEN (c1 IN ('a2','a4')) THEN

INTO t_ia_dest_2(flag,c) VALUES(flag2,c2)

ELSE

INTO t_ia_dest_3(flag,c) VALUES(flag1||flag2,c1||c2)

SELECT c1,c2, 'f1' flag1, 'f2' flag2 FROM t_ia_src;

-- 如果存在就更新,不存在就插入用一个语句实现

DROP TABLE t_mg;

CREATE TABLE t_mg(code VARCHAR2(10), NAME VARCHAR2(10));

SELECT * FROM t_mg;

MERGE INTO t_mg a

USING (SELECT 'the code' code, 'the name' NAME FROM dual) b

ON (a.code = b.code)

WHEN MATCHED THEN

UPDATE SET a.NAME = b.NAME

WHEN NOT MATCHED THEN

INSERT (code, NAME) VALUES (b.code, b.NAME);

-- 抽取/删除重复记录

DROP TABLE t_dup;

CREATE TABLE t_dup AS SELECT 'code_'||ROWNUM code, dbms_random.string('z',5) NAME FROM dual CONNECT BY ROWNUM<=10;

INSERT INTO t_dup SELECT 'code_'||ROWNUM code, dbms_random.string('z',5) NAME FROM dual CONNECT BY ROWNUM<=2;

SELECT * FROM t_dup;

SELECT * FROM t_dup a WHERE a.ROWID (SELECT MIN(b.ROWID) FROM t_dup b WHERE a.code=b.code);

SELECT b.code, b.NAME

FROM (SELECT a.code,

a.NAME,

row_number() over(PARTITION BY a.code ORDER BY a.ROWID) rn

FROM t_dup a) b

WHERE b.rn > 1;

-- IN/EXISTS的不同适用环境

-- t_orders.customer_id有索引

SELECT a.*

FROM t_employees a

WHERE a.employee_id IN

(SELECT b.sales_rep_id FROM t_orders b WHERE b.customer_id = 12);

SELECT a.*

FROM t_employees a

WHERE EXISTS (SELECT 1

FROM t_orders b

WHERE b.customer_id = 12

AND a.employee_id = b.sales_rep_id);

-- t_employees.department_id有索引

SELECT a.*

FROM t_employees a

WHERE a.department_id = 10

AND EXISTS

(SELECT 1 FROM t_orders b WHERE a.employee_id = b.sales_rep_id);

SELECT a.*

FROM t_employees a

WHERE a.department_id = 10

AND a.employee_id IN (SELECT b.sales_rep_id FROM t_orders b);

-- FBI

DROP TABLE t_fbi;

CREATE TABLE t_fbi AS

SELECT ROWNUM rn, dbms_random.STRING('z',10) NAME , SYSDATE + dbms_random.VALUE * 10 dt FROM dual

CONNECT BY ROWNUM <=10;

CREATE INDEX idx_nonfbi ON t_fbi(dt);

DROP INDEX idx_fbi_1;

CREATE INDEX idx_fbi_1 ON t_fbi(trunc(dt));

SELECT * FROM t_fbi WHERE trunc(dt) = to_date('-09-21','yyyy-mm-dd') ;

-- 不建议使用

SELECT * FROM t_fbi WHERE to_char(dt, 'yyyy-mm-dd') = '2006-09-21';

-- LOOP中的COMMIT/ROLLBACK

DROP TABLE t_loop PURGE;

create TABLE t_loop AS SELECT * FROM user_objects WHERE 1=2;

SELECT * FROM t_loop;

-- 逐行提交

DECLARE

BEGIN

FOR cur IN (SELECT * FROM user_objects) LOOP

INSERT INTO t_loop VALUES cur;

COMMIT;

END LOOP;

END;

-- 模拟批量提交blog.knowsky.com/

DECLARE

v_count NUMBER;

BEGIN

FOR cur IN (SELECT * FROM user_objects) LOOP

INSERT INTO t_loop VALUES cur;

v_count := v_count + 1;

IF v_count >= 100 THEN

COMMIT;

END IF;

END LOOP;

COMMIT;

END;

-- 真正的批量提交

DECLARE

CURSOR cur IS

SELECT * FROM user_objects;

TYPE rec IS TABLE OF user_objects%ROWTYPE;

recs rec;

BEGIN

OPEN cur;

WHILE (TRUE) LOOP

FETCH cur BULK COLLECT

INTO recs LIMIT 100;

-- forall 实现批量

FORALL i IN 1 .. recs.COUNT

INSERT INTO t_loop VALUES recs (i);

COMMIT;

EXIT WHEN cur%NOTFOUND;

END LOOP;

CLOSE cur;

END;

-- 悲观锁定/乐观锁定

DROP TABLE t_lock PURGE;

CREATE TABLE t_lock AS SELECT 1 ID FROM dual;

SELECT * FROM t_lock;

-- 常见的实现逻辑,隐含bug

DECLARE

v_cnt NUMBER;

BEGIN

-- 这里有并发性的bug

SELECT MAX(ID) INTO v_cnt FROM t_lock;

-- here for other operation

v_cnt := v_cnt + 1;

INSERT INTO t_lock (ID) VALUES (v_cnt);

COMMIT;

END;

-- 高并发环境下,安全的实现逻辑

DECLARE

v_cnt NUMBER;

BEGIN

-- 对指定的行取得lock

SELECT ID INTO v_cnt FROM t_lock WHERE ID=1 FOR UPDATE;

-- 在有lock的情况下继续下面的操作

SELECT MAX(ID) INTO v_cnt FROM t_lock;

-- here for other operation

v_cnt := v_cnt + 1;

INSERT INTO t_lock (ID) VALUES (v_cnt);

COMMIT; --提交并且释放lock

END;

-- 硬解析/软解析

DROP TABLE t_hard PURGE;

CREATE TABLE t_hard (ID INT);

SELECT * FROM t_hard;

DECLARE

sql_1 VARCHAR2(200);

BEGIN

-- hard parse

-- java中的同等语句是 Statement.execute()

FOR i IN 1 .. 1000 LOOP

sql_1 := 'insert into t_hard(id) values(' || i || ')';

EXECUTE IMMEDIATE sql_1;

END LOOP;

COMMIT;

-- soft parse

--java中的同等语句是 PreparedStatement.execute()

sql_1 := 'insert into t_hard(id) values(:id)';

FOR i IN 1 .. 1000 LOOP

EXECUTE IMMEDIATE sql_1

USING i;

END LOOP;

COMMIT;

END;

-- 正确的分页算法

SELECT *

FROM (SELECT a.*, ROWNUM rn

FROM (SELECT * FROM t_employees ORDER BY first_name) a

WHERE ROWNUM <= 500)

WHERE rn > 480 ;

-- 分页算法(why not this one)

SELECT a.*, ROWNUM rn

FROM (SELECT * FROM t_employees ORDER BY first_name) a

WHERE ROWNUM <= 500 AND ROWNUM > 480;

-- 分页算法(why not this one)

SELECT b.*

FROM (SELECT a.*, ROWNUM rn

FROM t_employees a

WHERE ROWNUM < = 500

ORDER BY first_name) b

WHERE b.rn > 480;

-- OLAP

-- 小计合计

SELECT CASE

WHEN a.deptno IS NULL THEN

'合计'

WHEN a.deptno IS NOT NULL AND a.empno IS NULL THEN

'小计'

ELSE

'' || a.deptno

END deptno,

a.empno,

a.ename,

SUM(a.sal) total_sal

FROM scott.emp a

GROUP BY GROUPING SETS((a.deptno),(a.deptno, a.empno, a.ename),());

-- 分组排序

SELECT a.deptno,

a.empno,

a.ename,

a.sal,

-- 可跳跃的rank

rank() over(PARTITION BY a.deptno ORDER BY a.sal DESC) r1,

-- 密集型rank

dense_rank() over(PARTITION BY a.deptno ORDER BY a.sal DESC) r2,

-- 不分组排序

rank() over(ORDER BY sal DESC) r3

FROM scott.emp a

ORDER BY a.deptno,a.sal DESC;

-- 当前行数据和前/后n行的数据比较

SELECT a.empno,

a.ename,

a.sal,

-- 上面一行

lag(a.sal) over(ORDER BY a.sal DESC) lag_1,

-- 下面三行

lead(a.sal, 3) over(ORDER BY a.sal DESC) lead_3

FROM scott.emp a

ORDER BY a.sal DESC;

篇2:Oracle SQL精妙SQL语句讲解

教程贴士:--行列转换 行转列DROP TABLE t_change_lc;CREATE TABLE t_change_lc (card_code VARCHAR2

--行列转换 行转列

DROP TABLE t_change_lc;

CREATE TABLE t_change_lc (card_code VARCHAR2(3), q NUMBER, bal NUMBER);

INSERT INTO t_change_lc

SELECT '001' card_code, ROWNUM q, trunc(dbms_random.VALUE * 100) bal FROM dual CONNECT BY ROWNUM <= 4

UNION

SELECT '002' card_code, ROWNUM q, trunc(dbms_random.VALUE * 100) bal FROM dual CONNECT BY ROWNUM <= 4;

SELECT * FROM t_change_lc;

SELECT a.card_code,

SUM(decode(a.q, 1, a.bal, 0)) q1,

SUM(decode(a.q, 2, a.bal, 0)) q2,

SUM(decode(a.q, 3, a.bal, 0)) q3,

SUM(decode(a.q, 4, a.bal, 0)) q4

FROM t_change_lc a

GROUP BY a.card_code

ORDER BY 1;

--行列转换 列转行

DROP TABLE t_change_cl;

CREATE TABLE t_change_cl AS

SELECT a.card_code,

SUM(decode(a.q, 1, a.bal, 0)) q1,

SUM(decode(a.q, 2, a.bal, 0)) q2,

SUM(decode(a.q, 3, a.bal, 0)) q3,

SUM(decode(a.q, 4, a.bal, 0)) q4

FROM t_change_lc a

GROUP BY a.card_code

ORDER BY 1;

SELECT * FROM t_change_cl;

SELECT t.card_code,

t.rn q,

decode(t.rn, 1, t.q1, 2, t.q2, 3, t.q3, 4, t.q4) bal

FROM (SELECT a.*, b.rn

FROM t_change_cl a,

(SELECT ROWNUM rn FROM dual CONNECT BY ROWNUM <= 4) b) t

ORDER BY 1, 2;

--行列转换 行转列 合并

DROP TABLE t_change_lc_comma;

CREATE TABLE t_change_lc_comma AS SELECT card_code,'quarter_'||q AS q FROM t_change_lc;

SELECT * FROM t_change_lc_comma;

SELECT t1.card_code, substr(MAX(sys_connect_by_path(t1.q, ';')), 2) q

FROM (SELECT a.card_code,

a.q,

row_number() over(PARTITION BY a.card_code ORDER BY a.q) rn

FROM t_change_lc_comma a) t1

START WITH t1.rn = 1

CONNECT BY t1.card_code = PRIOR t1.card_code

AND t1.rn - 1 = PRIOR t1.rn

GROUP BY t1.card_code;

--行列转换 列转行 分割

DROP TABLE t_change_cl_comma;

CREATE TABLE t_change_cl_comma AS

SELECT t1.card_code, substr(MAX(sys_connect_by_path(t1.q, ';')), 2) q

FROM (SELECT a.card_code,

a.q,

row_number() over(PARTITION BY a.card_code ORDER BY a.q) rn

FROM t_change_lc_comma a) t1

START WITH t1.rn = 1

CONNECT BY t1.card_code = PRIOR t1.card_code

AND t1.rn - 1 = PRIOR t1.rn

GROUP BY t1.card_code;

SELECT * FROM t_change_cl_comma;

SELECT t.card_code,

substr(t.q,

instr(';' || t.q, ';', 1, rn),

instr(t.q || ';', ';', 1, rn) - instr(';' || t.q, ';', 1, rn)) q

FROM (SELECT a.card_code, a.q, b.rn

FROM t_change_cl_comma a,

(SELECT ROWNUM rn FROM dual CONNECT BY ROWNUM <= 100) b

WHERE instr(';' || a.q, ';', 1, rn) > 0) t

ORDER BY 1, 2;

-- 实现一条记录根据条件多表插入

DROP TABLE t_ia_src;

CREATE TABLE t_ia_src AS SELECT 'a'||ROWNUM c1, 'b'||ROWNUM c2 FROM dual CONNECT BY ROWNUM<=5;

DROP TABLE t_ia_dest_1;

CREATE TABLE t_ia_dest_1(flag VARCHAR2(10) , c VARCHAR2(10));

DROP TABLE t_ia_dest_2;

CREATE TABLE t_ia_dest_2(flag VARCHAR2(10) , c VARCHAR2(10));

DROP TABLE t_ia_dest_3;

CREATE TABLE t_ia_dest_3(flag VARCHAR2(10) , c VARCHAR2(10));

SELECT * FROM t_ia_src;

SELECT * FROM t_ia_dest_1;

SELECT * FROM t_ia_dest_2;

SELECT * FROM t_ia_dest_3;

INSERT ALL

WHE

篇3:精妙SQL语句

说明:复制表(只复制结构,源表名:a 新表名:b)

select * into b from a where 11

说明:拷贝表(拷贝数据,源表名:a 目标表名:b)

insert into b(a, b, c) select d,e,f from b;

说明:显示文章、提交人和最后回复时间

select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b

说明:外连接查询(表名1:a 表名2:b)

select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

说明:日程安排提前五分钟提醒

select * from 日程安排 where datediff('minute',f开始时间,getdate)>5

说明:两张关联表,删除主表中已经在副表中没有的信息

delete from info where not exists ( select * from infobz where info.infid=infobz.infid )

说明:--

SQL:

SELECT A.NUM, A.NAME, B.UPD_DATE, B.PREV_UPD_DATE

FROM TABLE1,

(SELECT X.NUM, X.UPD_DATE, Y.UPD_DATE PREV_UPD_DATE

FROM (SELECT NUM, UPD_DATE, INBOUND_QTY, STOCK_ONHAND

FROM TABLE2

WHERE TO_CHAR(UPD_DATE,'YYYY/MM') = TO_CHAR(SYSDATE, 'YYYY/MM')) X,

(SELECT NUM, UPD_DATE, STOCK_ONHAND

FROM TABLE2

WHERE TO_CHAR(UPD_DATE,'YYYY/MM') =

TO_CHAR(TO_DATE(TO_CHAR(SYSDATE, 'YYYY/MM') || '/01','YYYY/MM/DD') - 1, 'YYYY/MM') ) Y,

WHERE X.NUM = Y.NUM (+)

AND X.INBOUND_QTY + NVL(Y.STOCK_ONHAND,0) X.STOCK_ONHAND ) B

WHERE A.NUM = B.NUM

说明:--

select * from studentinfo where not exists(select * from student where studentinfo.id=student.id) and 系名称='“&strdepartmentname&”' and 专业名称='“&strprofessionname&”' order by 性别,生源地,高考总成绩

从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源)

SELECT a.userper, a.tel, a.standfee, TO_CHAR(a.telfeedate, 'yyyy') AS telyear,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '01', a.factration)) AS JAN,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '02', a.factration)) AS FRI,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '03', a.factration)) AS MAR,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '04', a.factration)) AS APR,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '05', a.factration)) AS MAY,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '06', a.factration)) AS JUE,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '07', a.factration)) AS JUL,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '08', a.factration)) AS AGU,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '09', a.factration)) AS SEP,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '10', a.factration)) AS OCT,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '11', a.factration)) AS NOV,

SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '12', a.factration)) AS DEC

FROM (SELECT a.userper, a.tel, a.standfee, b.telfeedate, b.factration

FROM TELFEESTAND a, TELFEE b

WHERE a.tel = b.telfax) a

GROUP BY a.userper, a.tel, a.standfee, TO_CHAR(a.telfeedate, 'yyyy')

说明:四表联查问题

select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....

说明:得到表中最小的未使用的ID号

SELECT (CASE WHEN EXISTS(SELECT * FROM Handle b WHERE b.HandleID = 1) THEN MIN(HandleID) + 1 ELSE 1 END) as HandleID FROM Handle WHERE NOT HandleID IN (SELECT a.HandleID - 1 FROM Handle a)

一个SQL语句的问题:行列转换

select * from v_temp

上面的视图结果如下:

user_name role_name

-------------------------

系统管理员 管理员

feng 管理员

feng 一般用户

test 一般用户

想把结果变成这样:

user_name role_name

---------------------------

系统管理员 管理员

feng 管理员,一般用户

test 一般用户

===================

create table a_test(name varchar(20),role2 varchar(20))

insert into a_test values('李','管理员')

insert into a_test values('张','管理员')

insert into a_test values('张','一般用户')

insert into a_test values('常','一般用户')

create function join_str(@content varchar(100))

returns varchar()

as

begin

declare @str varchar(2000)

set @str=''

select @str=@str+','+rtrim(role2) from a_test where [name]=@content

select @str=right(@str,len(@str)-1)

return @str

end

go

--调用:

select [name],dbo.join_str([name]) role2 from a_test group by [name]

--select distinct name,dbo.uf_test(name) from a_test

快速比较结构相同的两表

结构相同的两表,一表有记录3万条左右,一表有记录2万条左右,我怎样快速查找两表的不同记录?

============================

给你一个测试方法,从northwind中的orders表取数据,

select * into n1 from orders

select * into n2 from orders

select * from n1

select * from n2

--添加主键,然后修改n1中若干字段的若干条

alter table n1 add constraint pk_n1_id primary key (OrderID)

alter table n2 add constraint pk_n2_id primary key (OrderID)

select OrderID from (select * from n1 union select * from n2) a group by OrderID having count(*) > 1

应该可以,而且将不同的记录的ID显示出来。

下面的适用于双方记录一样的情况,

select * from n1 where orderid in (select OrderID from (select * from n1 union select * from n2) a group by OrderID having count(*) > 1)

至于双方互不存在的记录是比较好处理的

--删除n1,n2中若干条记录

delete from n1 where orderID in ('10728','10730')

delete from n2 where orderID in ('11000','11001')

--*************************************************************

-- 双方都有该记录却不完全相同

select * from n1 where orderid in(select OrderID from (select * from n1 union select * from n2) a group by OrderID having count(*) > 1)

union

--n2中存在但在n1中不存的在10728,10730

select * from n1 where OrderID not in (select OrderID from n2)

union

--n1中存在但在n2中不存的在11000,11001

select * from n2 where OrderID not in (select OrderID from n1)

四种方法取表里n到m条纪录:

1.

select top m * into 临时表(或表变量) from tablename order by columnname -- 将top m笔插入

set rowcount n

select * from 表变量 order by columnname desc

2.

select top n * from (select top m * from tablename order by columnname) a order by columnname desc

3.如果tablename里没有其他identity列,那么:

select identity(int) id0,* into #temp from tablename

取n到m条的语句为:

select * from #temp where id0 >=n and id0 <= m

如果你在执行select identity(int) id0,* into #temp from tablename这条语句的时候报错,那是因为你的DB中间的select into/bulkcopy属性没有打开要先执行:

exec sp_dboption 你的DB名字,'select into/bulkcopy',true

4.如果表里有identity属性,那么简单:

select * from tablename where identitycol between n and m

如何删除一个表中重复的记录?

create table a_dist(id int,name varchar(20))

insert into a_dist values(1,'abc')

insert into a_dist values(1,'abc')

insert into a_dist values(1,'abc')

insert into a_dist values(1,'abc')

exec up_distinct 'a_dist','id'

select * from a_dist

create procedure up_distinct(@t_name varchar(30),@f_key varchar(30))

--f_key表示是分组字段o即主键字段

as

begin

declare @max integer,@id varchar(30) ,@sql varchar(7999) ,@type integer

select @sql = 'declare cur_rows cursor for select '+@f_key+' ,count(*) from ' +@t_name +' group by ' +@f_key +' having count(*) > 1'

exec(@sql)

open cur_rows

fetch cur_rows into @id,@max

while @@fetch_status=0

begin

select @max = @max -1

set rowcount @max

select @type = xtype from syscolumns where id=object_id(@t_name) and name=@f_key

if @type=56

select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+ @id

if @type=167

select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+''''+ @id +''''

exec(@sql)

fetch cur_rows into @id,@max

end

close cur_rows

deallocate cur_rows

set rowcount 0

end

select * from systypes

select * from syscolumns where id = object_id('a_dist')

查询数据的最大排序问题(只能用一条语句写)

CREATE TABLE hard (qu char (11) ,co char (11) ,je numeric(3, 0))

insert into hard values ('A','1',3)

insert into hard values ('A','2',4)

insert into hard values ('A','4',2)

insert into hard values ('A','6',9)

insert into hard values ('B','1',4)

insert into hard values ('B','2',5)

insert into hard values ('B','3',6)

insert into hard values ('C','3',4)

insert into hard values ('C','6',7)

insert into hard values ('C','2',3)

要求查询出来的结果如下:

qu co je

----------- ----------- -----

A 6 9

A 2 4

B 3 6

B 2 5

C 6 7

C 3 4

就是要按qu分组,每组中取je最大的前2位!!

而且只能用一句sql语句!!!

select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je)

求删除重复记录的sql语句?

怎样把具有相同字段的纪录删除,只留下一条。

例如,表test里有id,name字段

如果有name相同的记录 只留下一条,其余的删除。

name的内容不定,相同的记录数不定,

有没有这样的sql语句?

==============================

A:一个完整的解决方案:

将重复的记录记入temp1表:

select [标志字段id],count(*) into temp1 from [表名]

group by [标志字段id]

having count(*)>1

2、将不重复的记录记入temp1表:

insert temp1 select [标志字段id],count(*) from [表名] group by [标志字段id] having count(*)=1

3、作一个包含所有不重复记录的表:

select * into temp2 from [表名] where 标志字段id in(select 标志字段id from temp1)

4、删除重复表:

delete [表名]

5、恢复表:

insert [表名] select * from temp2

6、删除临时表:

drop table temp1

drop table temp2

================================

B:

create table a_dist(id int,name varchar(20))

insert into a_dist values(1,'abc')

insert into a_dist values(1,'abc')

insert into a_dist values(1,'abc')

insert into a_dist values(1,'abc')

exec up_distinct 'a_dist','id'

select * from a_dist

create procedure up_distinct(@t_name varchar(30),@f_key varchar(30))

--f_key表示是分组字段o即主键字段

as

begin

declare @max integer,@id varchar(30) ,@sql varchar(7999) ,@type integer

select @sql = 'declare cur_rows cursor for select '+@f_key+' ,count(*) from ' +@t_name +' group by ' +@f_key +' having count(*) > 1'

exec(@sql)

open cur_rows

fetch cur_rows into @id,@max

while @@fetch_status=0

begin

select @max = @max -1

set rowcount @max

select @type = xtype from syscolumns where id=object_id(@t_name) and name=@f_key

if @type=56

select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+ @id

if @type=167

select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+''''+ @id +''''

exec(@sql)

fetch cur_rows into @id,@max

end

close cur_rows

deallocate cur_rows

set rowcount 0

end

select * from systypes

select * from syscolumns where id = object_id('a_dist')

行列转换--普通

假设有张学生成绩表(CJ)如下

Name Subject Result

张三 语文 80

张三 数学 90

张三 物理 85

李四 语文 85

李四 数学 92

李四 物理 82

想变成

姓名 语文 数学 物理

张三 80 90 85

李四 85 92 82

declare @sql varchar(4000)

set @sql = 'select Name'

select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'

from (select distinct Subject from CJ) as a

select @sql = @sql+' from test group by name'

exec(@sql)

行列转换--合并

有表A,

id pid

1 1

1 2

1 3

2 1

2 2

3 1

如何化成表B:

id pid

1 1,2,3

2 1,2

3 1

创建一个合并的函数

create function fmerg(@id int)

returns varchar(8000)

as

begin

declare @str varchar(8000)

set @str=''

select @str=@str+','+cast(pid as varchar) from 表A where id=@id

set @str=right(@str,len(@str)-1)

return(@str)

End

go

--调用自定义函数得到结果

select distinct id,dbo.fmerg(id) from 表A

如何取得一个数据表的所有列名

方法如下:先从SYSTEMOBJECT系统表中取得数据表的SYSTEMID,然后再SYSCOLUMN表中取得该数据表的所有列名。

SQL语句如下:

declare @objid int,@objname char(40)

set @objname = 'tablename'

select @objid = id from sysobjects where id = object_id(@objname)

select 'Column_name' = name from syscolumns where id = @objid order by colid

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='users'

通过SQL语句来更改用户的密码

修改别人的,需要sysadmin role

EXEC sp_password NULL, 'newpassword', 'User'

如果帐号为SA执行EXEC sp_password NULL, 'newpassword', sa

怎么判断出一个表的哪些字段不允许为空?

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where IS_NULLABLE='NO' and TABLE_NAME=tablename

如何在数据库里找到含有相同字段的表?

a. 查已知列名的情况

SELECT b.name as TableName,a.name as columnname

From syscolumns a INNER JOIN sysobjects b

ON a.id=b.id

AND b.type='U'

AND a.name='你的字段名字'

未知列名查所有在不同表出现过的列名

Select o.name As tablename,s1.name As columnname

From syscolumns s1, sysobjects o

Where s1.id = o.id

And o.type = 'U'

And Exists (

Select 1 From syscolumns s2

Where s1.name = s2.name

And s1.id s2.id

)

查询第xxx行数据

假设id是主键:

select * from (select top xxx * from yourtable) aa where not exists(select 1 from (select top xxx-1 * from yourtable) bb where aa.id=bb.id)

如果使用游标也是可以的

fetch absolute [number] from [cursor_name]

行数为绝对行数

SQL Server日期计算

a. 一个月的第一天

SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)

b. 本周的星期一

SELECT DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)

c. 一年的第一天

SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)

d. 季度的第一天

SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)

e. 上个月的最后一天

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))

f. 去年的最后一天

SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))

g. 本月的最后一天

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))

h. 本月的第一个星期一

select DATEADD(wk, DATEDIFF(wk,0,

dateadd(dd,6-datepart(day,getdate()),getdate())

), 0)

i. 本年的最后一天

SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))。

获取表结构[把 'sysobjects' 替换 成 'tablename' 即可]

SELECT CASE IsNull(I.name, '')

When '' Then ''

Else '*'

End as IsPK,

Object_Name(A.id) as t_name,

A.name as c_name,

IsNull(SubString(M.text, 1, 254), '') as pbc_init,

T.name as F_DataType,

CASE IsNull(TYPEPROPERTY(T.name, 'Scale'), '')

WHEN '' Then Cast(A.prec as varchar)

ELSE Cast(A.prec as varchar) + ',' + Cast(A.scale as varchar)

END as F_Scale,

A.isnullable as F_isNullAble

FROM Syscolumns as A

JOIN Systypes as T

ON (A.xType = T.xUserType AND A.Id = Object_id('sysobjects') )

LEFT JOIN ( SysIndexes as I

JOIN Syscolumns as A1

ON ( I.id = A1.id and A1.id = object_id('sysobjects') and (I.status & 0x800) = 0x800 AND A1.colid <= I.keycnt) )

ON ( A.id = I.id AND A.name = index_col('sysobjects', I.indid, A1.colid) )

LEFT JOIN SysComments as M

ON ( M.id = A.cdefault and ObjectProperty(A.cdefault, 'IsConstraint') = 1 )

ORDER BY A.Colid ASC

提取数据库内所有表的字段详细说明的SQL语句

SELECT

(case when a.colorder=1 then d.name else '' end) N'表名',

a.colorder N'字段序号',

a.name N'字段名',

(case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else ''

end) N'标识',

(case when (SELECT count(*)

FROM sysobjects

WHERE (name in

(SELECT name

FROM sysindexes

WHERE (id = a.id) AND (indid in

(SELECT indid

FROM sysindexkeys

WHERE (id = a.id) AND (colid in

(SELECT colid

FROM syscolumns

WHERE (id = a.id) AND (name = a.name))))))) AND

(xtype = 'PK'))>0 then '√' else '' end) N'主键',

b.name N'类型',

a.length N'占用字节数',

COLUMNPROPERTY(a.id,a.name,'PRECISION') as N'长度',

isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as N'小数位数',

(case when a.isnullable=1 then '√'else '' end) N'允许空',

isnull(e.text,'') N'默认值',

isnull(g.[value],'') AS N'字段说明'

FROM syscolumns a

left join systypes b

on a.xtype=b.xusertype

inner join sysobjects d

on a.id=d.id and d.xtype='U' and d.name'dtproperties'

left join syscomments e

on a.cdefault=e.id

left join sysproperties g

on a.id=g.id AND a.colid = g.smallid

order by object_name(a.id),a.colorder

快速获取表test的记录总数[对大容量表非常有效]

快速获取表test的记录总数:

select rows from sysindexes where id = object_id('test') and indid in (0,1)

update 2 set KHXH=(ID+1)2 2行递增编号

update [23] set id1 = 'No.'+right('00000000'+id,6) where id not like 'No%' //递增

update [23] set id1= 'No.'+right('00000000'+replace(id1,'No.',''),6) //补位递增

delete from [1] where (id%2)=1

奇数

替换表名字段

update [1] set domurl = replace(domurl,'Upload/Imgswf/','Upload/Photo/') where domurl like '%Upload/Imgswf/%'

截位

SELECT LEFT(表名, 5)

篇4:精妙的SQL语句

最近更 新

sql字符串函数大全和使用方法示例

SQL Server存储过程入门学习

动态给表添加删除字段并同时修改它的插入

关于SQL 存储过程入门基础(流程控制)

数据库更新Sqlserver脚本总结

删除重复的记录,并保存第一条记录或保存最

sql语句查询数据库中的表名/列名/主键/自

SQL Server 还原数据库错误解决方法

SQL Server的复制功能

教你轻松恢复/修复SQL Server的MDF文件

热 点 排 行

SQL Server 图文安装教程

SQL Server 安装图解教程(附

sqlserver中distinct的用法(不重

SQL Server导入、导出、备份数据

SQL语句去掉重复记录,获取重复记

SQL Server数据库入门学习总结

SQL Server错误代码大全及解释(

sql convert函数使用小结

sql 时间函数 整理的比较全了

用SQL语句添加删除修改字段、一些

篇5:经典sql语句

1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)

法一:select * into b from a where 11(仅用于SQlServer)

法二:select top 0 * into b from a

2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用)

into b(a, b, c) select d,e,f from b;

3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)

into b(a, b, c) select d,e,f from b in ‘具体数据库’ where 条件

例子:..from b in “&Server.MapPath(”.“)&”data.mdb“ &” where..

4、说明:子查询(表名1:a 表名2:b)

select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)

5、说明:显示文章、提交人和最后回复时间

select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b

6、说明:外连接查询(表名1:a 表名2:b)

select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

7、说明:在线视图查询(表名1:a )

select * from (SELECT a,b,c FROM a) T where t.a > 1;

8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括

select * from table1 where time between time1 and time2

select a,b,c, from table1 where a not between 数值1 and 数值2

9、说明:in 的使用方法

select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)

10、说明:两张关联表,删除主表中已经在副表中没有的信息

from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )

11、说明:四表联查问题:

select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....

12、说明:日程安排提前五分钟提醒

SQL: select * from 日程安排 where datediff(minute,f开始时间,getdate)>5

13、说明:一条sql 语句搞定数据库分页

select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段

具体实现:

关于数据库分页:

declare @start int,@end int

@sql nvar600)

set @sql=’select top’+str(@end-@start+1)+’+from T where rid not in(select top’+str(@str-1)+’Rid from T where Rid>-1)’

exec sp_executesql @sql

注意:在top后不能直接跟一个变量,所以在实际应用中只有这样的进行特殊的处理。Rid为一个标识列,如果top后还有具体的字段,这样做是非常有好处的。因为这样可以避免 top的字段如果是逻辑索引的,查询的结果后实际表中的不一致(逻辑索引中的数据有可能和数据表中的不一致,而查询时如果处在索引则首先查询索引)

14、说明:前10条记录

select top 10 * form table1 where 范围

15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)

select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)

16、说明:包括所有在 TableA中但不在 TableB和TableC中的行并消除所有重复行而派生出一个结果表

(select a from tableA ) except (select a from tableB) except (select a from tableC)

17、说明:随机取出10条数据

select top 10 * from tablename order by newid()

18、说明:随机选择记录

select newid()

19、说明:删除重复记录

1), from tablename where id not in (select max(id) from tablename group by col1,col2,...)

2),select distinct * into temp from tablename

from tablename

into tablename select * from temp

评价: 这种操作牵连大量的数据的移动,这种做法不适合大容量但数据操作

3),例如:在一个外部表中导入数据,由于某些原因第一次只导入了一部分,但很难判断具体位置,这样只有在下一次全部导入,这样也就产生好多重复的字段,怎样删除重复字段

alter table tablename

--添加一个自增列

add column_b int identity(1,1)

from tablename where column_b not in(

select max(column_b) from tablename group by column1,column2,...)

alter table tablename drop column column_b

20、说明:列出数据库里所有的表名

select name from sysobjects where type=U // U代表用户

21、说明:列出表里的所有的列名

select name from syscolumns where id=object_id(TableName)

22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。

select type,sum(case vender when A then pcs else 0 end),sum(case vender when C then pcs else 0 end),sum(case vender when B then pcs else 0 end) FROM tablename group by type

显示结果:

type vender pcs

电脑 A 1

电脑 A 1

光盘 B 2

光盘 A 2

手机 B 3

手机 C 3

23、说明:初始化表table1

TRUNCATE TABLE table1

24、说明:选择从10到15的记录

select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc

篇6:sql语句经典

1、说明:复制表(只复制结构,源表名:a 新表名:b)(Access可用)

法一:select * into b from a where 11(仅用于SQlServer)

法二:select top 0 * into b from a

2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b)(Access可用)

insert into b(a, b, c)select d,e,f from b;

3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)

insert into b(a, b, c)select d,e,f from b in ‘具体数据库’where 条件

例子:..from b in'“&Server.MapPath(”.“)&”data.mdb“&”' where..

4、说明:子查询(表名1:a 表名2:b)

select a,b,c from a wherea IN (select d from b ) 或者:select a,b,c from a where a IN (1,2,3)

5、说明:显示文章、提交人和最后回复时间

selecta.title,a.username,b.adddate from table a,(select max(adddate) adddate fromtable where table.title=a.title) b

6、说明:外连接查询(表名1:a 表名2:b)

select a.a, a.b, a.c,b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

7、说明:在线视图查询(表名1:a )

select * from (SELECTa,b,c FROM a) T where t.a > 1;

8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括

select * from table1where time between time1 and time2

select a,b,c, from table1 where a not between 数值1 and 数值2

9、说明:in 的使用方法

select * from table1where a [not] in (‘值1’,’值2’,’值4’,’值6’)

10、说明:两张关联表,删除主表中已经在副表中没有的信息

delete from table1 wherenot exists ( select * from table2 where table1.field1=table2.field1 )

11、说明:四表联查问题:

select * from a leftinner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.dwhere .....

12、说明:日程安排提前五分钟提醒

SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5

13、说明:一条sql 语句搞定数据库分页

select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段

具体实现:

关于数据库分页:

declare @start int,@end int

@sql nvarchar(600)

set @sql=’select top’+str(@end-@start+1)+’+from T where ridnot in(select top’+str(@str-1)+’Rid from T where Rid>-1)’

exec sp_executesql @sql

注意:在top后不能直接跟一个变量,所以在实际应用中只有这样的进行特殊的处理。Rid为一个标识列,如果top后还有具体的字段,这样做是非常有好处的。因为这样可以避免 top的字段如果是逻辑索引的,查询的结果后实际表中的不一致(逻辑索引中的数据有可能和数据表中的不一致,而查询时如果处在索引则首先查询索引)

14、说明:前10条记录

select top 10 * form table1where 范围

15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)

select a,b,cfrom tablename ta where a=(select max(a) from tablename tb wheretb.b=ta.b)

16、说明:包括所有在 TableA中但不在 TableB和TableC中的`行并消除所有重复行而派生出一个结果表

(select a from tableA )except (select a from tableB) except (select a from tableC)

17、说明:随机取出10条数据

select top 10 * from tablename order by newid()

18、说明:随机选择记录

select newid()

19、说明:删除重复记录

1),delete from tablenamewhere id not in (select max(id) from tablename group by col1,col2,...)

2),selectdistinct * into temp from tablename

delete from tablename

insert into tablename select *from temp

评价: 这种操作牵连大量的数据的移动,这种做法不适合大容量但数据操作

3),例如:在一个外部表中导入数据,由于某些原因第一次只导入了一部分,但很难判断具体位置,这样只有在下一次全部导入,这样也就产生好多重复的字段,怎样删除重复字段

alter table tablename

--添加一个自增列

add column_b int identity(1,1)

delete from tablename wherecolumn_b not in(

select max(column_b) from tablename group by column1,column2,...)

alter table tablename drop column column_b

20、说明:列出数据库里所有的表名

select name fromsysobjects where type='U' // U代表用户

21、说明:列出表里的所有的列名

select name fromsyscolumns where id=object_id('TableName')

22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。

select type,sum(casevender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type

显示结果:

type vender pcs

电脑 A 1

电脑 A 1

光盘 B 2

光盘 A 2

手机 B 3

手机 C 3

23、说明:初始化表table1

TRUNCATE TABLE table1

24、说明:选择从10到15的记录

select top 5 * from(select top 15 * from table order by id asc) table_别名 order by id desc

用一个实例讲解Oracle数据库的PL/SQL语句块

检查Oracle数据库中不合理的sql语句数据库教程

DB2数据库SQL注入语句

select count from table where ..这句sql语句的作用

50个常用sql语句

经典sql语句

sql连接语句

学语言的方法

全面了解初中议论文相关题型

实验心得总结

Oracle SQL精妙SQL语句讲解
《Oracle SQL精妙SQL语句讲解.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

【Oracle SQL精妙SQL语句讲解(精选6篇)】相关文章:

Java开发毕业论文参考文献2023-06-07

软件开发实习报告2024-04-07

提高航空发动机性能的弯扭导向器技术2022-11-09

计算机实验心得与总结2022-07-02

SQL?Server数据库教学方法探索2023-12-24

uniqueidentifier 数据类型数据库教程2022-09-27

Oracle深入学习2023-03-24

存储过程实现分页2022-05-03

一个常用的报表统计SQL语句2022-05-30

如何学好数据库2023-03-21

点击下载本文文档