SQL语句集锦
--语 句 功 能
--数据操作
SELECT --从数据库表中检索数据行和列
INSERT --向数据库表添加新数据行
DELETE --从数据库表中删除数据行
UPDATE --更新数据库表中的数据
--数据定义
CREATE TABLE --创建一个数据库表
DROP TABLE --从数据库中删除表
ALTER TABLE --修改数据库表结构
CREATE VIEW --创建一个视图
DROP VIEW --从数据库中删除视图
CREATE INDEX --为数据库表创建一个索引
DROP INDEX --从数据库中删除索引
CREATE PROCEDURE --创建一个存储过程
DROP PROCEDURE --从数据库中删除存储过程
CREATE TRIGGER --创建一个触发器
DROP TRIGGER --从数据库中删除触发器
CREATE SCHEMA --向数据库添加一个新模式
DROP SCHEMA --从数据库中删除一个模式
CREATE DOMAIN --创建一个数据值域
ALTER DOMAIN --改变域定义
DROP DOMAIN --从数据库中删除一个域
--数据控制
GRANT --授予用户访问权限
DENY --拒绝用户访问
REVOKE --解除用户访问权限
--事务控制
COMMIT --结束当前事务
ROLLBACK --中止当前事务
SET TRANSACTION --定义当前事务数据访问特征
--程序化SQL
DECLARE --为查询设定游标
EXPLAN --为查询描述数据访问计划
OPEN --检索查询结果打开一个游标
FETCH --检索一行查询结果
CLOSE --关闭游标
PREPARE --为动态执行准备SQL 语句
EXECUTE --动态地执行SQL 语句
DESCRIBE --描述准备好的查询
---局部变量
declare @id char(10)
--set @id = '10010001'
select @id = '10010001'
---全局变量
---必须以@@开头
--IF ELSE
declare @x int @y int @z int
select @x = 1 @y = 2 @z=3
if @x > @y
print 'x > y' --打印字符串'x > y'
else if @y > @z
print 'y > z'
else print 'z > y'
--CASE
use pangu
update employee
set e_wage =
case
when job_level = ’1’ then e_wage*1.08
when job_level = ’2’ then e_wage*1.07
when job_level = ’3’ then e_wage*1.06
else e_wage*1.05
end
--WHILE CONTINUE BREAK
declare @x int @y int @c int
select @x = 1 @y=1
while @x < 3
begin
print @x --打印变量x 的值
while @y < 3
begin
select @c = 100*@x + @y
print @c --打印变量c 的值
select @y = @y + 1
end
select @x = @x + 1
select @y = 1
end
--WAITFOR
--例 等待1 小时2 分零3 秒后才执行SELECT 语句
waitfor delay ’01:02:03’
select * from employee
--例 等到晚上11 点零8 分后才执行SELECT 语句
waitfor time ’23:08:00’
select * from employee
***SELECT***
select *(列名) from table_name(表名) where column_name operator value
ex:(宿主)
select * from stock_information where stockid = str(nid)
stockname = 'str_name'
stockname like '% find this %'
stockname like '[a-zA-Z]%' --------- ([]指定值的范围)
stockname like '[^F-M]%' --------- (^排除指定范围)
--------- 只能在使用like关键字的where子句中使用通配符)
or stockpath = 'stock_path'
or stocknumber < 1000
and stockindex = 24
not stock*** = 'man'
stocknumber between 20 and 100
stocknumber in(10,20,30)
order by stockid desc(asc) --------- 排序,desc-降序,asc-升序
order by 1,2 --------- by列号
stockname = (select stockname from stock_information where stockid = 4)
--------- 子查询
--------- 除非能确保内层select只返回一个行的值,
--------- 否则应在外层where子句中用一个in限定符
select distinct column_name form table_name --------- distinct指定检索独有的列值,不重复
select stocknumber ,"stocknumber + 10" = stocknumber + 10 from table_name
select stockname , "stocknumber" = count(*) from table_name group by stockname
--------- group by 将表按行分组,指定列中有相同的值
having count(*) = 2 --------- having选定指定的组
select *
from table1, table2
where table1.id *= table2.id -------- 左外部连接,table1中有的而table2中没有得以null表示
table1.id =* table2.id -------- 右外部连接
select stockname from table1
union [all] ----- union合并查询结果集,all-保留重复行
select stockname from table2
***insert***
insert into table_name (Stock_name,Stock_number) value ("xxx","xxxx")
value (select Stockname , Stocknumber from Stock_table2)---value为select语句
***update***
update table_name set Stockname = "xxx" [where Stockid = 3]
Stockname = default
Stockname = null
Stocknumber = Stockname + 4
***delete***
delete from table_name where Stockid = 3
truncate table_name ----------- 删除表中所有行,仍保持表的完整性
drop table table_name --------------- 完全删除表
***alter table*** --- 修改数据库表结构
alter table database.owner.table_name add column_name char(2) null .....
sp_help table_name ---- 显示表已有特征
create table table_name (name char(20), age smallint, lname varchar(30))
insert into table_name select ......... ----- 实现删除列的方法(创建新表)
alter table table_name drop constraint Stockname_default ---- 删除Stockname的default约束
***function(/*常用函数*/)***
----统计函数----
AVG --求平均值
COUNT --统计数目
MAX --求最大值
MIN --求最小值
SUM --求和
--AVG
use pangu
select avg(e_wage) as dept_avgWage
from employee
group by dept_id
--MAX
--求工资最高的员工姓名
use pangu
select e_name
from employee
where e_wage =
(select max(e_wage)
from employee)
--STDEV()
--STDEV()函数返回表达式中所有数据的标准差
--STDEVP()
--STDEVP()函数返回总体标准差
--VAR()
--VAR()函数返回表达式中所有值的统计变异数
--VARP()
--VARP()函数返回总体变异数
----算术函数----
/***三角函数***/
SIN(float_expression) --返回以弧度表示的角的正弦
COS(float_expression) --返回以弧度表示的角的余弦
TAN(float_expression) --返回以弧度表示的角的正切
COT(float_expression) --返回以弧度表示的角的余切
/***反三角函数***/
ASIN(float_expression) --返回正弦是FLOAT 值的以弧度表示的角
ACOS(float_expression) --返回余弦是FLOAT 值的以弧度表示的角
ATAN(float_expression) --返回正切是FLOAT 值的以弧度表示的角
ATAN2(float_expression1,float_expression2)
--返回正切是float_expression1 /float_expres-sion2的以弧度表示的角
DEGREES(numeric_expression)
--把弧度转换为角度返回与表达式相同的数据类型可为
--INTEGER/MONEY/REAL/FLOAT 类型
RADIANS(numeric_expression) --把角度转换为弧度返回与表达式相同的数据类型可为
--INTEGER/MONEY/REAL/FLOAT 类型
EXP(float_expression) --返回表达式的指数值
LOG(float_expression) --返回表达式的自然对数值
LOG10(float_expression)--返回表达式的以10 为底的对数值
SQRT(float_expression) --返回表达式的平方根
/***取近似值函数***/
CEILING(numeric_expression) --返回>=表达式的最小整数返回的数据类型与表达式相同可为
--INTEGER/MONEY/REAL/FLOAT 类型
FLOOR(numeric_expression) --返回<=表达式的最小整数返回的数据类型与表达式相同可为
--INTEGER/MONEY/REAL/FLOAT 类型
ROUND(numeric_expression) --返回以integer_expression 为精度的四舍五入值返回的数据
--类型与表达式相同可为INTEGER/MONEY/REAL/FLOAT 类型
ABS(numeric_expression) --返回表达式的绝对值返回的数据类型与表达式相同可为
--INTEGER/MONEY/REAL/FLOAT 类型
SIGN(numeric_expression) --测试参数的正负号返回0 零值1 正数或-1 负数返回的数据类型
--与表达式相同可为INTEGER/MONEY/REAL/FLOAT 类型
PI() --返回值为π 即3.1415926535897936
RAND([integer_expression]) --用任选的[integer_expression]做种子值得出0-1 间的随机浮点数
----字符串函数----
ASCII() --函数返回字符表达式最左端字符的ASCII 码值
CHAR() --函数用于将ASCII 码转换为字符
--如果没有输入0 ~ 255 之间的ASCII 码值CHAR 函数会返回一个NULL 值
LOWER() --函数把字符串全部转换为小写
UPPER() --函数把字符串全部转换为大写
STR() --函数把数值型数据转换为字符型数据
LTRIM() --函数把字符串头部的空格去掉
RTRIM() --函数把字符串尾部的空格去掉
LEFT(),RIGHT(),SUBSTRING() --函数返回部分字符串
CHARINDEX(),PATINDEX() --函数返回字符串中某个指定的子串出现的开始位置
SOUNDEX() --函数返回一个四位字符码
--SOUNDEX函数可用来查找声音相似的字符串但SOUNDEX函数对数字和汉字均只返回0 值
DIFFERENCE() --函数返回由SOUNDEX 函数返回的两个字符表达式的值的差异
--0 两个SOUNDEX 函数返回值的第一个字符不同
--1 两个SOUNDEX 函数返回值的第一个字符相同
--2 两个SOUNDEX 函数返回值的第一二个字符相同
--3 两个SOUNDEX 函数返回值的第一二三个字符相同
--4 两个SOUNDEX 函数返回值完全相同
QUOTENAME() --函数返回被特定字符括起来的字符串
/*select quotename('abc', '{') quotename('abc')
运行结果如下
----------------------------------{
{abc} [abc]*/
REPLICATE() --函数返回一个重复character_expression 指定次数的字符串
/*select replicate('abc', 3) replicate( 'abc', -2)
运行结果如下
----------- -----------
abcabcabc NULL*/
REVERSE() --函数将指定的字符串的字符排列顺序颠倒
REPLACE() --函数返回被替换了指定子串的字符串
/*select replace('abc123g', '123', 'def')
运行结果如下
----------- -----------
abcdefg*/
SPACE() --函数返回一个有指定长度的空白字符串
STUFF() --函数用另一子串替换字符串指定位置长度的子串
----数据类型转换函数----
CAST() 函数语法如下
CAST() (<expression> AS <data_ type>[ length ])
CONVERT() 函数语法如下
CONVERT() (<data_ type>[ length ], <expression> [, style])
select cast(100+99 as char) convert(varchar(12), getdate())
运行结果如下
------------------------------ ------------
199 Jan 15 2000
----日期函数----
DAY() --函数返回date_expression 中的日期值
MONTH() --函数返回date_expression 中的月份值
YEAR() --函数返回date_expression 中的年份值
DATEADD(<datepart> ,<number> ,<date>)
--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期
DATEDIFF(<datepart> ,<number> ,<date>)
--函数返回两个指定日期在datepart 方面的不同之处
DATENAME(<datepart> , <date>) --函数以字符串的形式返回日期的指定部分
DATEPART(<datepart> , <date>) --函数以整数值的形式返回日期的指定部分
GETDATE() --函数以DATETIME 的缺省格式返回系统当前的日期和时间
----系统函数----
APP_NAME() --函数返回当前执行的应用程序的名称
COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值
COL_LENGTH(<'table_name'>, <'column_name'>) --函数返回表中指定字段的长度值
COL_NAME(<table_id>, <column_id>) --函数返回表中指定字段的名称即列名
DATALENGTH() --函数返回数据表达式的数据的实际长度
DB_ID(['database_name']) --函数返回数据库的编号
DB_NAME(database_id) --函数返回数据库的名称
HOST_ID() --函数返回服务器端计算机的名称
HOST_NAME() --函数返回服务器端计算机的名称
IDENTITY(<data_type>[, seed increment]) [AS column_name])
--IDENTITY() 函数只在SELECT INTO 语句中使用用于插入一个identity column列到新表中
/*select identity(int, 1, 1) as column_name
into newtable
from oldtable*/
ISDATE() --函数判断所给定的表达式是否为合理日期
ISNULL(<check_expression>, <replacement_value>) --函数将表达式中的NULL 值用指定值替换
ISNUMERIC() --函数判断所给定的表达式是否为合理的数值
NEWID() --函数返回一个UNIQUEIDENTIFIER 类型的数值
NULLIF(<expression1>, <expression2>)
--NULLIF 函数在expression1 与expression2 相等时返回NULL 值若不相等时则返回expression1 的值
精妙SQL语句
说明:复制表(只复制结构,源表名:a 新表名:b)
SQL: select * into b from a where 1<>1
说明:拷贝表(拷贝数据,源表名:a 目标表名:b)
SQL: insert into b(a, b, c) select d,e,f from b;
说明:显示文章、提交人和最后回复时间
SQL: 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)
SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
说明:日程安排提前五分钟提醒
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5
说明:两张关联表,删除主表中已经在副表中没有的信息
SQL:
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
说明:--
SQL:
select * from studentinfo where not exists(select * from student where studentinfo.id=student.id) and 系名称='"&strdepartmentname&"' and 专业名称='"&strprofessionname&"' order by 性别,生源地,高考总成绩
说明:
从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源)
SQL:
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')
说明:四表联查问题:
SQL: 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号
SQL:
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)
: 我在ms sql中建了一个表,可由于种种原因有些记录重复了
: 记录完全的一模一样。
: 现在我想把重复的都删掉,只保留重复记录中的第一条。
: 我在database好象看到有介绍oracle的,
select distinct * into #table_name from table_name
delete from table_name
select * into table_name from #table_name
drop table #table_name
与此相关的是“select into”选项,可以在数据库属性
对话框中,勾起来此项,或者在Query Analyzer中执行
execute sp_dboption 'db_name','select into','true'
开启。默认值是关闭的。
主 题:专贴揭示SQL语句,贴出你的精妙SQL,欢迎来抢分!
作 者:csdntoll (低调惯了)
等 级:
信 誉 值:147
所属论坛:Web 开发 ASP
问题点数:200
回复次数:260
发表时间:2003-3-18 18:02:24
格式
说明:复制表(只复制结构,源表名:a 新表名:b)
SQL: select * into b from a where 1<>1
回复人: LuoGD(沃适) ( ) 信誉:100 2003-3-18 18:07:37 得分:5
说明:拷贝表(拷贝数据,源表名:a 目标表名:b)
insert into b(a, b, c) select d,e,f from b;
Top
回复人: LuoGD(沃适) ( ) 信誉:100 2003-3-18 18:09:37 得分:5
说明:合并数据(表名1:a 表名2:b)
select a,b,c from a union select d,e,f from b;
Top
回复人: LuoGD(沃适) ( ) 信誉:100 2003-3-18 18:11:36 得分:5
说明:子查询(表名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)
Top
回复人: _TMG_(Alan) ( ) 信誉:120 2003-3-18 18:11:55 得分:0
这都是精妙?
Top
回复人: junsisi(君三思) ( ) 信誉:100 2003-3-18 18:12:36 得分:5
俺来贴个让俺对sql茅塞顿开的例子
说明:显示文章、提交人和最后回复时间
sql:select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
Top
回复人: LuoGD(沃适) ( ) 信誉:100 2003-3-18 18:13:48 得分:0
说明:外连接查询(表名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
Top
回复人: LuoGD(沃适) ( ) 信誉:100 2003-3-18 18:15:56 得分:0
说明:在线视图查询(表名1:a )
select * from (SELECT a,b,c FROM a) T where t.a > 1;
Top
回复人: gcs925(Study Java&Jsp ing) ( ) 信誉:105 2003-3-18 18:16:00 得分:0
mark
Top
回复人: net_lover(孟子E章) ( ) 信誉:727 2003-3-18 18:16:14 得分:0
SQL:SELECT NEWID()
Top
回复人: snakegod(蛇姬) ( ) 信誉:100 2003-3-18 21:49:41 得分:0
????
没有深度 没兴趣
Top
回复人: _TMG_(Alan) ( ) 信誉:120 2003-3-18 21:54:21 得分:0
我宁愿用数据库冗余也不会使用子查询,除非万不得已
Top
回复人: nittystone(没有想法) ( ) 信誉:115 2003-3-18 22:20:49 得分:5
自连接取出荣于数据
把所有姓名相同的只取出一个
select a.name from table_name a where a.id in
(select b.id from table_name b where a.id<>b.id)
同理删除荣誉数据
delete from table_name where table_name.id in
(select b.id from table_name b where table_name.id<>b.id)
Top
回复人: allforly(白衣胜血) ( ) 信誉:126 2003-3-19 1:18:29 得分:0
今天开眼界了啊,我就会select * from ** where **=**这一句
Top
回复人: gddd(gddd) ( ) 信誉:100 2003-3-19 2:07:30 得分:0
利害...我会多一句
select top n * form ** where XXX
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-19 9:22:40 得分:0
不错,不错,
蛮喜欢junsisi(君三思)的这句:
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
对net_lover(孟子E章)前辈,这句不理解,我菜,呵呵
SQL:SELECT NEWID()
Top
回复人: cpp2017(幕白兄) ( ) 信誉:145 2003-3-19 9:27:39 得分:0
SELECT DISTINCT TSD.Time_Sheet_Dtl_Record_No,TSD.User_Record_No,TP.Period_Start_Date ,TP.Period_End_Date INTO #temp FROM Time_Sheet_Details TSD, Time_Sheet_Period TP ,User_Group_User_Relationship UGUR,User_Group_Master UGM ,User_Data_Access_Right UDAR WHERE TSD.status ='TS_WFMGRA' AND DATEDIFF(dd,TP.period_start_date,TSD.work_Date)>=0 AND DATEDIFF(dd,TP.period_end_date,TSD.work_Date)<=0 AND UGUR.User_Record_No = TSD.User_Record_No AND UGM.User_Group_Record_No=UGUR.User_Group_Record_No AND UGM.User_Group_Name IN('Technician','Engineer') AND UDAR.User_Record_No = TSD.User_Record_No AND UDAR.Division_Record_No IN(1) SELECT DISTINCT A.User_Record_No, B.Staff_No, B.Full_Name,B.Job_Title, SUM(working_hour) AS Working_Hours,SUM(ot) AS OT_HOURS, C.Period_Start_Date,C.Period_End_Date INTO #temp2 FROM Time_Sheet_Details A INNER JOIN User_Master B ON B.User_Record_No= A.User_Record_No INNER JOIN #temp C ON C.Time_Sheet_Dtl_Record_No = A.Time_Sheet_Dtl_Record_No GROUP BY A.User_Record_No, B.Staff_No,B.Full_Name,B.Job_Title, C.Period_Start_Date,C.Period_End_Date HAVING COUNT(*) = DATEDIFF(d,C.Period_Start_Date,C.Period_End_Date)+1 Select A.User_Record_No,A.Staff_No,A.Full_Name,A.Job_Title ,A.Working_Hours,A.OT_HOURS,A.Period_Start_Date,A.Period_End_Date ,DM.Division_Code INTO #temp3 FROM #temp2 AS A INNER JOIN User_Data_Access_Right UDAR ON UDAR.User_Record_No = A.User_Record_No INNER JOIN Division_Master DM ON DM.Division_Record_No = UDAR.Division_Record_No SELECT * From #temp3 order by 1,7,8; Select Count(Distinct User_Record_No+Period_Start_Date+Period_End_Date) From #temp3 DROP TABLE #temp ,#temp2,#temp3
Top
回复人: cloud1002(好得掉渣~) ( ) 信誉:100 2003-3-19 9:35:06 得分:0
mark
Top
回复人: smallmuda(飞翔的猪) ( ) 信誉:101 2003-3-19 9:37:27 得分:0
select * from a where time between time1 and time2
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-19 9:40:15 得分:0
让你们看看什么是SQL经典吧..
http://expert.csdn.net/Expert/TopicView1.asp?id=928809
Top
回复人: cpp2017(幕白兄) ( ) 信誉:145 2003-3-19 9:41:08 得分:5
select isNull(A.name,B.name),isnull(a.code,B.code) from table1 A
full out join table2 B on
A.id = B.id
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-19 9:43:29 得分:0
to cpp2017(长安不见使人愁)
jeff?
Top
回复人: zhw_yihui(卜卢特) ( ) 信誉:94 2003-3-19 9:53:25 得分:0
SQL:SELECT NEWID()
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-19 9:58:59 得分:0
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
选择在每一组b值相同的数据中对应的a最大的(换成average或别的函数或子查询,你会有意想不到的发现)记录的所有信息.
类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.
上面的许多同志对子查询存在有偏见与误解,其实在一个好的数据分析程序中,子查询可以简化很多程序逻辑.
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-19 10:01:40 得分:0
上面select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
这种相关子查询和delete(insert)等结合起来,可以用于消除数据库中某个字段(或某些)的重复值
Top
回复人: hubinasm(火星撞地球) ( ) 信誉:115 2003-3-19 10:10:41 得分:0
(select a from tableA ) except (select a from tableB) except (select a from tableC)
Top
回复人: aocool(知秋一叶) ( ) 信誉:100 2003-3-19 10:14:11 得分:0
获益不浅啊.
SELECT DISTINCT TSD.Time_Sheet_Dtl_Record_No,TSD.User_Record_No,TP.Period_Start_Date ,TP.Period_End_Date INTO #temp FROM Time_Sheet_Details TSD, Time_Sheet_Period TP ,User_Group_User_Relationship UGUR,User_Group_Master UGM ,User_Data_Access_Right UDAR WHERE TSD.status ='TS_WFMGRA' AND DATEDIFF(dd,TP.period_start_date,TSD.work_Date)>=0 AND DATEDIFF(dd,TP.period_end_date,TSD.work_Date)<=0 AND UGUR.User_Record_No = TSD.User_Record_No AND UGM.User_Group_Record_No=UGUR.User_Group_Record_No AND UGM.User_Group_Name IN('Technician','Engineer') AND UDAR.User_Record_No = TSD.User_Record_No AND UDAR.Division_Record_No IN(1) SELECT DISTINCT A.User_Record_No, B.Staff_No, B.Full_Name,B.Job_Title, SUM(working_hour) AS Working_Hours,SUM(ot) AS OT_HOURS, C.Period_Start_Date,C.Period_End_Date INTO #temp2 FROM Time_Sheet_Details A INNER JOIN User_Master B ON B.User_Record_No= A.User_Record_No INNER JOIN #temp C ON C.Time_Sheet_Dtl_Record_No = A.Time_Sheet_Dtl_Record_No GROUP BY A.User_Record_No, B.Staff_No,B.Full_Name,B.Job_Title, C.Period_Start_Date,C.Period_End_Date HAVING COUNT(*) = DATEDIFF(d,C.Period_Start_Date,C.Period_End_Date)+1 Select A.User_Record_No,A.Staff_No,A.Full_Name,A.Job_Title ,A.Working_Hours,A.OT_HOURS,A.Period_Start_Date,A.Period_End_Date ,DM.Division_Code INTO #temp3 FROM #temp2 AS A INNER JOIN User_Data_Access_Right UDAR ON UDAR.User_Record_No = A.User_Record_No INNER JOIN Division_Master DM ON DM.Division_Record_No = UDAR.Division_Record_No SELECT * From #temp3 order by 1,7,8; Select Count(Distinct User_Record_No+Period_Start_Date+Period_End_Date) From #temp3 DROP TABLE #temp ,#temp2,#temp3
:)
cpp2017(长安不见使人愁)这么长一句,少见,能否介绍介绍它的功力?^_^
SELECT DISTINCT TSD.Time_Sheet_Dtl_Record_No,TSD.User_Record_No,TP.Period_Start_Date ,TP.Period_End_Date INTO #temp FROM Time_Sheet_Details TSD, Time_Sheet_Period TP ,User_Group_User_Relationship UGUR,User_Group_Master UGM ,User_Data_Access_Right UDAR WHERE TSD.status ='TS_WFMGRA' AND DATEDIFF(dd,TP.period_start_date,TSD.work_Date)>=0 AND DATEDIFF(dd,TP.period_end_date,TSD.work_Date)<=0 AND UGUR.User_Record_No = TSD.User_Record_No AND UGM.User_Group_Record_No=UGUR.User_Group_Record_No AND UGM.User_Group_Name IN('Technician','Engineer') AND UDAR.User_Record_No = TSD.User_Record_No AND UDAR.Division_Record_No IN(1) SELECT DISTINCT A.User_Record_No, B.Staff_No, B.Full_Name,B.Job_Title, SUM(working_hour) AS Working_Hours,SUM(ot) AS OT_HOURS, C.Period_Start_Date,C.Period_End_Date INTO #temp2 FROM Time_Sheet_Details A INNER JOIN User_Master B ON B.User_Record_No= A.User_Record_No INNER JOIN #temp C ON C.Time_Sheet_Dtl_Record_No = A.Time_Sheet_Dtl_Record_No GROUP BY A.User_Record_No, B.Staff_No,B.Full_Name,B.Job_Title, C.Period_Start_Date,C.Period_End_Date HAVING COUNT(*) = DATEDIFF(d,C.Period_Start_Date,C.Period_End_Date)+1 Select A.User_Record_No,A.Staff_No,A.Full_Name,A.Job_Title ,A.Working_Hours,A.OT_HOURS,A.Period_Start_Date,A.Period_End_Date ,DM.Division_Code INTO #temp3 FROM #temp2 AS A INNER JOIN User_Data_Access_Right UDAR ON UDAR.User_Record_No = A.User_Record_No INNER JOIN Division_Master DM ON DM.Division_Record_No = UDAR.Division_Record_No SELECT * From #temp3 order by 1,7,8; Select Count(Distinct User_Record_No+Period_Start_Date+Period_End_Date) From #temp3 DROP TABLE #temp ,#temp2,#temp3
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-19 11:14:05 得分:0
我认为上面的语句在实现需求时并不是最简,效率最高的语句.
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-19 11:45:29 得分:0
各种查询技巧结合才能写出最高效的查询
在SQL中使用DISTINCT是代价比较高的查询方式
Top
回复人: oldsky(九指神丐) ( ) 信誉:54 2003-3-19 13:13:09 得分:0
微软不公布SQLserver2000中的函数:
print pwdcompare('helloworld', pwdencrypt('helloworld'))
print pwdcompare('hello', pwdencrypt('world'))
Top
回复人: funboy88(司令) ( ) 信誉:121 2003-3-19 13:20:20 得分:0
pwdencrypt
密码加密?
有些什么作用,不明白
随机取出10条数据
select top 10 * from tablename order by newid()
Top
回复人: mzcih(小马过河) ( ) 信誉:110 2003-3-19 13:25:31 得分:0
看君一张贴,胜看一天书。
Top
回复人: funboy88(司令) ( ) 信誉:121 2003-3-19 13:26:48 得分:5
功能:
type vender pcs
电脑 A 1
电脑 A 1
光盘 B 2
光盘 A 2
手机 B 3
手机 C 3
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
Top
回复人: funboy88(司令) ( ) 信誉:121 2003-3-19 13:30:27 得分:0
FUNCTION:DELELTE REPEAT RECORDS
DELETE from tablename where id not in (select max(id) from tablename group by col1,col2,...)
Top
回复人: chonboy(一只来自南方的羊) ( ) 信誉:100 2003-3-19 14:32:56 得分:0
Microsoft SQL Server是如何加密口令的?未公开的加密函数?
如果对MSSQL的用户信息有兴趣的,可能会发现master.dbo.sysxlogins里面存放着用户的口令,可是呢,password字段如果不是null就是一堆看不懂的binary,这个口令是怎么加密的呢?
其实只要仔细看看master.dbo.sp_addlogin就知道了,MSSQL的sp都可以看到代码,真是不错。
让我们来看看它是怎么做的,注意这一行select @passwd = pwdencrypt(@passwd),这个时后@passwd就被加密了,让我们也来试一下
DECLARE @ClearPWD varchar(255)
DECLARE @EncryptedPWD varbinary(255)
SELECT @ClearPWD = 'test'
SELECT @EncryptedPWD = CONVERT(varbinary(255), pwdencrypt(@ClearPWD))
SELECT @EncryptedPWD
看上去不错,确实被加密了,可是我怎么还原呢?
呵呵,这就没戏了,口令加密都是单向的,用加密后的密文来比较就可以了。
继续看看其它用户相关的sp,可以发现master.dbo.sp_password里面有口令比较的内容。
pwdcompare(@old, password, (CASE WHEN xstatus&2048 = 2048 THEN 1 ELSE 0 END))
不用去理会xstatus,这是一个状态掩码,一般我们用的时候就直接用0就可以了
DECLARE @ClearPWD varchar(255)
DECLARE @EncryptedPWD varbinary(255)
SELECT @ClearPWD = 'test'
SELECT @EncryptedPWD = CONVERT(varbinary(255), pwdencrypt(@ClearPWD))
SELECT pwdcompare(@ClearPWD, @EncryptedPWD, 0)
SELECT pwdcompare('ErrorPassword', @EncryptedPWD, 0)
这样我们就可以使用这两个函数来加密自己的密码了,怎么样,还不错吧?
引用自
http://www.bgchina.com/daily/bd_1/
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-20 10:00:45 得分:0
SELECT语法:(基本)
SELECT [DISTINCT]
(column [{, column } ] )| *
FROM table [ { , table} ]
[ORDER BY column [ASC] | [DESC
[{ , column [ASC] | [DESC } ] ]
WHERE predicate [ { logical-connector predicate } ];
------------------------------------------------------
INSERT语法:
INSERT INTO table
[(column { ,column})]
VALUES
(columnvalue [{,columnvalue}]);
------------------------------------------------------
UPDATE语法:
UPDATE table
SET column = value [{, column = value}]
[ WHERE predicate [ { logical-connector predicate}]];
------------------------------------------------------
DELETE语法:
DELETE FROM table
[WHERE predicate [ { logical-connector predicate} ] ];
------------------------------------------------------
Top
回复人: liuzxit(每日晕十几次) ( ) 信誉:115 2003-3-20 10:13:05 得分:0
想把我那兩頁長的SELECT語句拿出來了﹐不過沒興趣
Top
回复人: lgj1012(oοО○≮国产超人≯○Оοo) ( ) 信誉:99 2003-3-20 10:13:41 得分:0
MARK MARK
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-20 10:41:56 得分:0
常识补充
统计函数:
AVG(字段名) 得出一个表格栏平均值
COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计
MAX(字段名) 取得一个表格栏最大的值
MIN(字段名) 取得一个表格栏最小的值
SUM(字段名) 把数据栏的值相加
eg:
sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"
Top
回复人: carl__yao(頭目) ( ) 信誉:95 2003-3-20 10:50:06 得分:0
select top 0 * into b from a
Top
回复人: flashasp(flashasp) ( ) 信誉:95 2003-3-20 13:05:01 得分:0
select name from sysobjects where type='U''列出数据库里所有的表名
select name from syscolumns where id=object_id('TableName')'列出表里的所有的
Top
回复人: flashasp(flashasp) ( ) 信誉:95 2003-3-20 13:05:47 得分:0
select name from sysobjects where type='U''列出数据库里所有的表名
select name from syscolumns where id=object_id('TableName')'列出表里的所有的字段名
Top
回复人: annkie(无声的雨) ( ) 信誉:113 2003-3-20 13:27:22 得分:0
帮忙看看这个帖子,解决了我想贴在这里应该是可以的 :)
http://expert.csdn.net/Expert/topic/1554/1554516.xml?temp=.6041071
Top
回复人: flyinto(孤独求败) ( ) 信誉:100 2003-3-20 14:14:42 得分:0
MARK
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-20 14:15:00 得分:0
source data
kzx4dm xbdm jylsfsdm ...
11 2 10
11 2 10
12 2 10
12 1 20
12 1 20
destination:
kzx4dm bys_count yjs_count jy_ratio
11 2 2 1.00
12 3 1 1/3
SELECT DISTINCT kzx4dm,(SELECT COUNT(jylsfsdm) FROM tablename WHERE kzx4dm=TA.kzx4dm) AS bys_count,(SELECT COUNT(jylsfsdm) FROM tablename WHERE kzx4dm=TA.kzx4dm WHERE jylsfsdm=10) AS yjs_count,yjs_count/bys_count AS jy_ratio
FROM tablename AS TA
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-20 14:18:35 得分:10
to annkie(活着便精彩)
看看上面的语句是否解决了问题?
纠正一下,应该是
SELECT DISTINCT kzx4dm,(SELECT COUNT(jylsfsdm) FROM tablename WHERE kzx4dm=TA.kzx4dm) AS bys_count,(SELECT COUNT(jylsfsdm) FROM tablename WHERE kzx4dm=TA.kzx4dm AND jylsfsdm=10) AS yjs_count,yjs_count/bys_count AS jy_ratio
FROM tablename AS TA
Top
回复人: GageCSDN(稻草人) ( ) 信誉:100 2003-3-20 17:30:45 得分:0
seeing........
Top
回复人: allserver(server) ( ) 信誉:100 2003-3-20 19:13:25 得分:0
8错
Top
回复人: kirc(无聊中...) ( ) 信誉:100 2003-3-20 19:16:32 得分:0
关注....
Top
回复人: annkie(无声的雨) ( ) 信誉:113 2003-3-20 19:28:23 得分:0
To yonghengdizhen:
thank you.
正在研究此问题中.
yjs_count/bys_count AS jy_ratio 这句无法通过检查,不过可以把前面的东西拿倒这里来搞定,不使用字段名.
你的sql语句是对的.
Top
回复人: flyycyu(fly) ( ) 信誉:100 2003-3-21 9:36:40 得分:0
gz
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-21 10:02:00 得分:0
我决定:把200分中的180分,奖给贴出最精妙的SQL的高手!
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-21 11:00:52 得分:0
二维表 T(F1,F2,F3,F4,F5,F6,F7) 表示如下关系:
学生ID 学生姓名 课程ID 课程名称 成绩 教师ID 教师姓名
S3 王五 K4 政治 53 T4 赵老师
S1 张三 K1 数学 61 T1 张老师
S2 李四 K3 英语 88 T3 李老师
S1 张三 K4 政治 77 T4 赵老师
S2 李四 K4 政治 67 T5 周老师
S3 王五 K2 语文 90 T2 王老师
S3 王五 K1 数学 55 T1 张老师
S1 张三 K2 语文 81 T2 王老师
S4 赵六 K2 语文 59 T1 王老师
S1 张三 K3 英语 37 T3 李老师
S2 李四 K1 数学 81 T1 张老师
请以一句 T-SQL (Ms SQL Server) 或 Jet SQL (Ms Access) 在 原表 T 基础上作答
1.如果 T 表还有一字段 F0 数据类型为自动增量整型(唯一,不会重复),
而且 T 表中含有除 F0 字段外,请删除其它字段完全相同的重复多余的脏记录数据:
delete from t where f0 in(select max(f0) from t group by f1,f2,f3,f4,f5,f6,f7 having count(f0)>1)
2.列印各科成绩最高和最低的记录: (就是各门课程的最高、最低分的学生和老师)
课程ID,课程名称,最高分,学生ID,学生姓名,教师ID,教师姓名,最低分,学生ID,学生姓名,教师ID,教师姓名
select tb.f4,tb.f3,tb1.f5,tb.f1,tb.f2,tb.f6,tb.f7,tb2.f5,tb2.f1,tb2.f2,tb2.f6,tb2.f7 from t tb where
f5=(select max(f5) from t where t.f4=tb.f4)
join select f2,f7 from t tb2 where
f5=(select min(f5) from t where t.f4=tb2.f4)
on tb.f4=tb2.f4
先完成一个,想想在做下一个.
3.按成绩从高到低顺序,列印所有学生四门(数学,语文,英语,政治)课程成绩: (就是每个学生的四门课程的成绩单)
学生ID,学生姓名,数学,语文,英语,政治,有效课程数,有效平均分
(注: 有效课程即在 T 表中有该学生的成绩记录,如不明白可不列印"有效课程数"和"有效平均分")
select tb1.f1,tb1.f2,count(tb1.f5) as scores,sum(tb1.f5) as scoresum, avg(tb1.f5) AS average,
tb2.f5,tb3.f5,tb4.f5,tb5.f5
from t as tb1
left join t as tb2
on tb1.f0=tb2.f0 and tb2.f3=k4
left join t as tb3
on tb1.f0=tb3.f0 and tb3.f3=k3
left join t as tb4
on tb1.f0=tb4.f0 and tb4.f3=k2
left join t as tb5
on tb1.f0=tb5.f0 and tb5.f3=k1
grout by tb1.f2 order by tb1.scoresum desc
4.按各科不及格率的百分数从低到高和平均成绩从高到低顺序,统计并列印各科平均成绩和不及格率的百分数(用"N行"表示): (就是分析哪门课程难)
课程ID,课程名称,平均成绩,及格百分数
select f3,f4, (select count(f1) from t where t.f4=tb.f4 and f5<60)/(select count(f1) from t where t.f4=tb.f4) as failper,((select sum(f5) from t where t.f4=tb.f4)/ (select count(f5) from t where t.f4=tb.f4)) as averagescore
from t tb order by failper asc, as averagescore desc
Top
回复人: wenhao676(zzc) ( ) 信誉:93 2003-3-21 11:01:50 得分:0
/****** Object: Stored Procedure dbo.dt_checkoutobject Script Date: 2003-3-12 9:25:26 ******/
create proc dbo.dt_checkoutobject
@chObjectType char(4),
@vchObjectName varchar(255),
@vchComment varchar(255),
@vchLoginName varchar(255),
@vchPassword varchar(255),
@iVCSFlags int = 0,
@iActionFlag int = 0/* 0 => Checkout, 1 => GetLatest, 2 => UndoCheckOut */
as
set nocount on
declare @iReturn int
declare @iObjectId int
select @iObjectId =0
declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'
declare @iReturnValue int
select @iReturnValue = 0
declare @vchTempText varchar(255)
/* this is for our strings */
declare @iStreamObjectId int
select @iStreamObjectId = 0
declare @iPropertyObjectId int
select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')
declare @vchProjectName varchar(255)
declare @vchSourceSafeINI varchar(255)
declare @vchServerName varchar(255)
declare @vchDatabaseName varchar(255)
exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject', @vchProjectName OUT
exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT
exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT
if @chObjectType = 'PROC'
begin
/* Procedure Can have up to three streams
Drop Stream, Create Stream, GRANT stream */
exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT
if @iReturn <> 0 GOTO E_OAError
exec @iReturn = sp_OAMethod @iObjectId,
'CheckOut_StoredProcedure',
NULL,
@sProjectName = @vchProjectName,
@sSourceSafeINI = @vchSourceSafeINI,
@sObjectName = @vchObjectName,
@sServerName = @vchServerName,
@sDatabaseName = @vchDatabaseName,
@sComment = @vchComment,
@sLoginName = @vchLoginName,
@sPassword = @vchPassword,
@iVCSFlags = @iVCSFlags,
@iActionFlag = @iActionFlag
if @iReturn <> 0 GOTO E_OAError
exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT
if @iReturn <> 0 GOTO E_OAError
create table #commenttext (id int identity, sourcecode varchar(255))
select @vchTempText = 'STUB'
while @vchTempText IS NOT NULL
begin
exec @iReturn = sp_OAMethod @iStreamObjectId, 'GetStream', @iReturnValue OUT, @vchTempText OUT
if @iReturn <> 0 GOTO E_OAError
if (@vchTempText IS NOT NULL) insert into #commenttext (sourcecode) select @vchTempText
end
select 'VCS'=sourcecode from #commenttext order by id
select 'SQL'=text from syscomments where id = object_id(@vchObjectName) order by colid
end
CleanUp:
return
E_OAError:
exec dbo.dt_displayoaerror @iObjectId, @iReturn
GOTO CleanUp
GO
看的我直晕~!
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-21 11:17:12 得分:0
1.如果 T 表还有一字段 F0 数据类型为自动增量整型(唯一,不会重复),
而且 T 表中含有除 F0 字段外,请删除其它字段完全相同的重复多余的脏记录数据:
delete from t where f0 in(select max(f0) from t group by f1,f2,f3,f4,f5,f6,f7 having count(f0)>1)
上面这个sql有问题
正确的如下
DELETE Legal_Dispute_Lawyer WHERE Lawyer_Record_No IN(SELECT Lawyer_Record_No FROM Legal_Dispute_Lawyer LDL WHERE Lawyer_Record_No(SELECT TOP 1 Lawyer_Record_No FROM Legal_Dispute_Lawyer WHERE LD=LDL.LD AND Name=LDL.Name AND Email=LDL.Email AND Phone_No=LDL.Phone_No AND Fax_No=LDL.Fax_No))
消除Legal_Dispute_Lawyer 表中除Lawyer_Record_No(自增字段)外其余数据完全相同的记录.
表结构如下
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Legal_Dispute_Lawyer]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Legal_Dispute_Lawyer]
GO
CREATE TABLE [dbo].[Legal_Dispute_Lawyer] (
[Lawyer_Record_No] [int] IDENTITY (1, 1) NOT NULL ,
[LD] [int] NOT NULL ,
[Name] [int] NOT NULL ,
[Phone_No] [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
[Fax_No] [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
[varchar] (255) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
以这种方式还可以实现组内消除重复值..
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-21 11:19:48 得分:0
DELETE Legal_Dispute_Lawyer WHERE Lawyer_Record_No IN(SELECT Lawyer_Record_No FROM Legal_Dispute_Lawyer LDL WHERE Lawyer_Record_No<>(SELECT TOP 1 Lawyer_Record_No FROM Legal_Dispute_Lawyer WHERE LD=LDL.LD AND Name=LDL.Name AND Email=LDL.Email AND Phone_No=LDL.Phone_No AND Fax_No=LDL.Fax_No))
Top
回复人: ylecho(~猫猫) ( ) 信誉:100 2003-3-21 13:58:37 得分:0
select * from table;
xixi
Top
回复人: SeaSee(纵横四海) ( ) 信誉:100 2003-3-21 14:10:19 得分:0
table1
kzx4dm xbdm jylsfsdm ...
10 2 8
11 2 9
12 2 19
13 1 18
14 1 19
select top 3 with ties jylsfsdm from table1
结果:
kzx4dm xbdm jylsfsdm ...
12 2 19
14 1 19
13 1 18
11 2 9
说明:取出并列排行的所有记录
Top
回复人: lsqteng(阿琦) ( ) 信誉:102 2003-3-21 14:18:11 得分:0
说到语法我就来兴趣了,哈哈,请看:
SELECT statement::=
<query_experssion>
[ORDER BY {order_by_expression|Column_position[ASC|DESC]}
[,...n]]
[COMPUTE
{{AVG|COUNT|MAX|MIN|SUM}(exression)}[,...n]
[BY expression[,...n]]
]
[FOR {BROWSE |XML{RAW|AUTO|EXPLICIT}
[,XMLDATA]
[,ELEMENTS]
[,BINARY base64]
}
]
[OPTION(<query_hint>[,...n])]
<query expression>::=
{<query specification>|(<query expression>)}
[UNION[ALL]<query specification|(<query expression<)[...n]]
<query specification>::=
SELECT [ALL|DISTINCT]
[{TOP integer|TOP integer PERCENT}[WITH TIES]]
<select _list>
[INTO new_table]
[FROM{<table_source>}[,...n]]
[WHERE <search_condition>]
[GROUP BY [ALL]group_by_expression[,...n]
[WITH{CUBE|ROLLUP}]
]
[HAVING<search_condition>}
哎,行了吧,这还是select 语句的形式。要看完全的,喔,那可不得了喔。我不写了,累死了,呵呵
Top
回复人: vulcan(东方不败) ( ) 信誉:126 2003-3-21 14:24:43 得分:0
关注.
Top
回复人: zhangguagua(瓜瓜) ( ) 信誉:131 2003-3-21 14:37:53 得分:0
收藏
Top
回复人: shark7823(魔鬼的脸蛋,天使的身材) ( ) 信誉:97 2003-3-21 14:45:12 得分:0
这种好贴,不mark,不行啊
Top
回复人: bingeng(大眼镜) ( ) 信誉:102 2003-3-21 14:47:42 得分:0
UP
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-21 15:24:55 得分:0
敬请高手出贴,最好是存储过程
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-21 15:31:32 得分:0
存储过程其实没什么经典不经典.
无非是把你在VBS中实现的逻辑在sql服务端实现而已..
而高效的存储过程往往还是使用传统的sql语法来实现主要逻辑.
Top
回复人: windyao(猫) ( ) 信誉:94 2003-3-21 16:02:22 得分:0
8错8错
Top
是那个家伙对数据下了手脚^_^
create table IKnowYou
(userid varchar(30),
TableName varchar(50),
Action varchar(6),
DateT datatime,
TrrigerTableColumns.....,
TrrigerTableColumns.....)
create trriger Who_Do_It on table
for update
as
declare userid varchar(30)
declare TableName varchar(50)
declare Action varchar(6)
userid=@@suser_sname
Action='update'
TableName='tabel'
insert into IKnowYou values(userid,TableName,Action,Now,select * from deleted,select * from inserted)
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-21 17:06:52 得分:0
kill all connections to a given databse
CREATE PROCEDURE usp_killDBConnections @DBName varchar(50), @withmsg bit=1
AS
SET NOCOUNT ON
DECLARE @spidstr varchar(8000)
DECLARE @ConnKilled smallint
SET @ConnKilled=0
SET @spidstr = ''
IF db_id(@DBName) < 4
BEGIN
PRINT 'Connections to system databases cannot be killed'
RETURN
END
SELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE dbid=db_id(@DBName)
IF LEN(@spidstr) > 0
BEGIN
EXEC(@spidstr)
SELECT @ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE dbid=db_id(@DBName)
END
IF @withmsg =1
PRINT CONVERT(VARCHAR(10), @ConnKilled) + ' Connection(s) killed for DB ' + @DBName
GO
Top
回复人: matq2008(叶子.net) ( ) 信誉:100 2003-3-21 18:00:47 得分:0
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
Top
回复人: cnuninet(www.helloaspx.com) ( ) 信誉:100 2003-3-21 18:26:32 得分:0
SELECT * FROM table ORDER BY id
SELECT * FROM table ORDER BY id DESC
正反排序,厉害吧!
Top
回复人: cnuninet(www.helloaspx.com) ( ) 信誉:100 2003-3-21 18:26:54 得分:0
还有,一次选出表中的所有内容:
SELECT * FROM table
Top
回复人: learnner( ) ( ) 信誉:110 2003-3-21 18:42:16 得分:0
mark
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-21 18:42:41 得分:0
楼上的哥们,厉害!^_^
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-21 18:45:07 得分:0
不是说你,是说: cnuninet(www.helloaspx.com) ,呵呵
Top
回复人: miqier1209(米琪儿) ( ) 信誉:100 2003-3-21 22:58:39 得分:0
select * into b from a where 1<>1
这样生成的b表访问的用户没有select的权限?
请问sql DX们这个问题怎么解决?
Top
回复人: whcasp(money is best~) ( ) 信誉:105 2003-3-22 9:25:25 得分:0
厉害
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-22 10:09:48 得分:0
Select left(field,1) as field1 from table_name order by field desc
Top
回复人: ministrybill(生命的烙印) ( ) 信誉:120 2003-3-22 10:23:58 得分:0
唉,好像称不上经典
大家来捧捧场:http://expert.csdn.net/Expert/topic/1545/1545418.xml?temp=.6732141
Top
回复人: legend9(legend) ( ) 信誉:100 2003-3-22 11:13:44 得分:0
select count(clubmember.clubid)as hot,clubmember.clubid,clubinfo.clubid,clubinfo.name from clubmember,clubinfo where clubinfo.clubid=clubmember.clubid group by clubmember.clubid order by hot DESC limit 10
Top
回复人: waterfall_cp(鸟鸟) ( ) 信誉:98 2003-3-22 11:36:37 得分:0
条件删除
DELETE DBO.TEMP WHERE FLD_CHARACTER IN
(
SELECT FLD_CHARACTER
FROM dbo.TBL_CHARACTER
WHERE (FLD_DELETED = 1) AND (FLD_LEVEL <= 18) AND
(FLD_UPDATEDATETIME <= GETDATE() - 5)
)
Top
回复人: georgechen(小雨点) ( ) 信誉:100 2003-3-22 15:39:49 得分:0
选择前数据库里前10条记录:
1、select top 10 * from table
2、set rowcount 10
select * from table
Top
回复人: dh20156(风之石-ASP.net学习中) ( ) 信誉:5 2003-3-22 16:13:21 得分:0
今天才把合计函数搞定:
Set rs=conn.execute("Select min(id) as minID from TABLE") ^_^
Top
回复人: boy21cnthp(娃娃) ( ) 信誉:99 2003-3-22 17:06:00 得分:0
高手
Top
回复人: honghaier(红孩儿) ( ) 信誉:100 2003-3-22 18:23:01 得分:0
select SQL高手 from 本版发贴者
Where 得分>0
Top
回复人: sevenhzheleven(水冰) ( ) 信誉:100 2003-3-24 1:54:26 得分:0
哇,,,,高手,你们是工作的时候学的,还是读书的时候开始学的?请教
Top
回复人: ljupin(无情刀) ( ) 信誉:106 2003-3-24 2:09:57 得分:0
select * form *
会执行吗
Top
回复人: dawooo(大宇) ( ) 信誉:100 2003-3-24 8:15:58 得分:0
大宇阅览
Top
回复人: wfnuser(夏雪) ( ) 信誉:103 2003-3-24 8:52:17 得分:5
select * from 日程安排 where datediff('minute',f开始时间,getdate())>5
日程安排提前五分钟提醒。
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-24 9:52:31 得分:0
to miqier1209(米琪儿) ( ) 信誉:100 2003-03-21 22:58:00 得分:0
select * into b from a where 1<>1
这样生成的b表访问的用户没有select的权限?
请问sql DX们这个问题怎么解决?
指定dbo前缀应该可以解决问题了..
Top
回复人: accp258(男人背后的女人) ( ) 信誉:101 2003-3-24 11:17:19 得分:0
mark!
Top
回复人: suasalito(妈的,什么血这么难喝,喝可乐去) ( ) 信誉:100 2003-3-24 11:19:59 得分:0
同学们回答的都不错,恩,值得表扬
Top
回复人: hotel9545(清风剑客) ( ) 信誉:100 2003-3-24 12:10:38 得分:0
复制一张表
create table aaa as select * from bbb;
Top
回复人: fenlin(千里之行,始于足下......) ( ) 信誉:110 2003-3-24 12:21:33 得分:0
我也来凑热闹,呵呵......
<%
'取出随机记录
Randomize
RNumber = Int(Rnd*200) + 1
SQL = "SELECT * FROM Customers WHERE ID = " & RNumber
set objRec = ObjConn.Execute(SQL)
Response.WriteRNumber & " = " & objRec("ID") & " " & objRec("c_email")
%>
Top
回复人: linens(存储过程) ( ) 信誉:100 2003-3-24 13:33:10 得分:0
上面的人把视图都搬出来了啊不过几乎都是查询,我来点实用的
insert into pbrule(newrid,subj,bz,zf,orid,rstat,layer,bid) select newrid,subj,bz,zf,orid,rstat,layer,bid from pbrule1 where bruleid=bruleid
将pbrule1 表中符合条件的记录 导入 pbrule表中
Top
回复人: linens(存储过程) ( ) 信誉:100 2003-3-24 13:38:49 得分:0
下面这个更实用,就是两张关联表,删除主表中已经在副表中没有的信息
delete from info where not exists ( select * from infobz where info.infid=infobz.infid )
这条语句就是删除 INFO表中infid字段在infobz中不存在的记录
此语句用来维护数据库很有用哦。
楼主给点分吧
Top
回复人: qigang_liu(云山云海) ( ) 信誉:100 2003-3-24 15:19:57 得分:5
CREATE OR REPLACE PROCEDURE DUMP_TO_WEB_TCLHD_SP_OBJ
AS
BEGIN
CALC_PIA_PRICE ;
DELETE FROM TCLHD_SP_OBJ ;
INSERT INTO TCLHD_SP_OBJ (NAME,CODE,ID,PRICE,TYPE,FIELDS) (
SELECT c.DESCRIPTION,C.SEGMENT1,a.INVENTORY_ITEM_ID, nvl(c.ATTRIBUTE14,'0'),0,nvl(c.ATTRIBUTE13,0)
from mtl_item_categories a , mtl_categories b , mtl_system_items c
where a.CATEGORY_ID = b.CATEGORY_ID and b.SEGMENT1='原材料'
and a.INVENTORY_ITEM_ID = c.INVENTORY_ITEM_ID AND A.ORGANIZATION_ID = 21
and c.ORGANIZATION_ID = 21 and c.inventory_item_status_code = 'Active' );
COMMIT ;
END ;
Top
回复人: wnhoo(e梦缘) ( ) 信誉:115 2003-3-24 15:38:58 得分:0
数据库IBM DB2 》》》SQL
绝对精华
select dmbh,SJDM,flsm,dmzz from ydm where dmbh=3300
union all
select dmbh,SJDM,flsm,dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh=3300)
union all
select dmbh,SJDM,flsm,dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in (
select dmzz from ydm where dmbh=3300))
union all
select dmbh,SJDM,flsm,dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in (
select dmzz from ydm where dmbh=3300)))
union all
select dmbh,SJDM,flsm,dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in (
select dmzz from ydm where dmbh=3300))))
**********************************
select SJDM from ydm where dmbh=3300
union all
select SJDM from ydm where dmbh in
(select dmzz from ydm where dmbh=3300)
union all
select SJDM from ydm where dmbh in
(select dmzz from ydm where dmbh in (
select dmzz from ydm where dmbh=3300))
union all
select SJDM from ydm where dmbh in
(select dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in (
select dmzz from ydm where dmbh=3300)))
union all
select SJDM from ydm where dmbh in
(select dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in
(select dmzz from ydm where dmbh in (
select dmzz from ydm where dmbh=3300))))
**************************************************
SELECT COUNT(*) as yhs ,SUM(DF) as df FROM DB2.DFTDF
WHERE (year(rq)*12+month(rq)) between 24015 and 24015
AND dflb=513
and (ZHH,YYH) IN
(SELECT ZHH,YYxH FROM DB2.YDD111 WHERE HYM in
( select SJDM from DB2.ydm where dmbh=3200
union all
select SJDM from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh=3200)
union all
select SJDM from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh=3200))
union all
select SJDM from DB2.ydm where dmbh in (
Select dmzz from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh=3200)))
union all
select SJDM from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh in (
select dmzz from DB2.ydm where dmbh=3200))))
))
***********************************************
select bcm,bsm,count(bsm) as sl
from (
select bcm,case
when blx='DXB' and bxh like 'DD%' AND BXH NOT LIKE 'DDS%'
then 'JJB'
else 'DZB'
end as bsm
from jldb) as jldb2
group by bcm,bsm
select bcm,bsm,count(bsm) as sl
from (
select bcm,case
when blx='DXB' and bxh like 'DD%' AND BXH NOT LIKE 'DDS%'
then 'JJB'
else 'DZB'
end as bsm
from jldb
where bzt='OK' and qyrq between '1999-1-1' and '2003-1-3' ) as jldb2
group by bcm,bsm
****************
select bcm,bsm,bxh,count(bsm) as sl
from (
select bcm,case
when blx='DXB' and bxh like 'DD%' AND BXH NOT LIKE 'DDS%'
then 'JJB'
else 'DZB'
end as bsm,bxh
from jldb
where bzt='OK' and qyrq between '1999-1-1' and '2003-1-3' ) as jldb2
group by bcm,bxh,bsm
**********************************************
with ttt as (select bcm,bxh,bsm,count(bsm) as sl from (select bcm,bxh,case when blx='DXB' and bxh like 'DD%' AND BXH NOT LIKE 'DDS%' then '机械表' else 'DZB' end
as bsm from jldb where bzt='OK' and qyrq<='2002-2-2' ) as jldb2 group by bcm,bxh,bsm),
sss as (select bcm,bxh,bsm,count(bsm) as sl1 from (select bcm,bxh,case when blx='DXB' and bxh like 'DD%' AND BXH NOT LIKE 'DDS%' then '机械表' else 'DZB' end
as bsm from jldb where bzt='OK' and qyrq<='2000-1-1' ) as jldb2 group by bcm,bxh,bsm)
select ttt.bcm,ttt.bxh,ttt.bsm,value(ttt.sl,0) as sl1,value(sss.sl1,0) as sl2,(value(ttt.sl,0)-value(sss.sl1,0)) as sl3 from ttt full join sss
on sss.bxh=ttt.bxh and sss.bcm=ttt.bcm and sss.bsm=ttt.bsm order by ttt.bcm,ttt.bxh,ttt.bsm
Top
回复人: guzh() ( ) 信誉:100 2003-3-24 17:45:41 得分:0
看了
Top
回复人: realljx(至尊十三少) ( ) 信誉:102 2003-3-24 18:52:15 得分:0
好长
Top
回复人: shawshanke(我随风而来,随风而去) ( ) 信誉:100 2003-3-24 19:44:53 得分:0
恭喜此帖突破100大观!
--------------------------------------------------
我随风而来,又随风而去!
Top
回复人: cep50(cep50) ( ) 信誉:100 2003-3-24 20:30:58 得分:0
上当了,该软件没什么用。是在骗取别人的智慧,还要收人家的人民币。
Top
回复人: eafin(e峰.Net)(一叶枫舟) ( ) 信誉:115 2003-3-24 21:00:38 得分:0
收藏啦!
希望谁能把这些整理一下。然后我再收藏,呵呵
Top
回复人: rolandzhang() ( ) 信誉:103 2003-3-24 21:22:06 得分:0
wenhao676能否加些注释?我菜一点。
Top
回复人: coffee_black(黑咖啡) ( ) 信誉:100 2003-3-25 0:07:54 得分:0
是好贴!!
Top
回复人: zhw_yihui(卜卢特) ( ) 信誉:94 2003-3-25 8:34:10 得分:0
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
选择在每一组b值相同的数据中对应的a最大的(换成average或别的函数或子查询,你会有意想不到的发现)记录的所有信息.
类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.
上面的许多同志对子查询存在有偏见与误解,其实在一个好的数据分析程序中,子查询可以简化很多程序逻辑.
Top
回复人: gage(蓝宝石) ( ) 信誉:100 2003-3-25 11:17:11 得分:0
收藏
Top
回复人: fvsl(楚龙) ( ) 信誉:98 2003-3-25 13:09:51 得分:0
我收藏:)
Top
回复人: zhusuhao(不以为然) ( ) 信誉:101 2003-3-25 13:51:32 得分:0
藏
Top
回复人: fule(孤魂野鬼) ( ) 信誉:100 2003-3-25 13:59:59 得分:0
藏
Top
回复人: 98130(Oracle) ( ) 信誉:100 2003-3-25 14:33:53 得分:0
回复人: fenlin(千里之行,始于足下......) ( ) 信誉:100 2003-03-24 12:21:00 得分:0
我也来凑热闹,呵呵......
<%
'取出随机记录
Randomize
RNumber = Int(Rnd*200) + 1
SQL = "SELECT * FROM Customers WHERE ID = " & RNumber
set objRec = ObjConn.Execute(SQL)
Response.WriteRNumber & " = " & objRec("ID") & " " & objRec("c_email")
%>
这种方法存在bug,有可能取不出数据来,
最好还是还
select top 1 * from tablename order by newid()
Top
回复人: hisi(海山) ( ) 信誉:100 2003-3-25 16:05:23 得分:0
收藏...
Top
回复人: lyexcel(冰上飞人) ( ) 信誉:100 2003-3-25 16:36:58 得分:0
select * from
(select top 5 * from
(select * from
(select top 5 *
from GuestBook
where 1=1 and Deleted = false
order by GuestID desc)
order by GuestID asc)
order by GuestID asc)
order by GuestID desc
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-25 18:37:44 得分:0
select * from
(select top 5 * from
(select * from
(select top 5 *
from GuestBook
where 1=1 and Deleted = false
order by GuestID desc)
order by GuestID asc)
order by GuestID asc)
order by GuestID desc
这可是一个经典的SQL.
大概再加几层嵌套,查询引擎都可以崩溃了..
Top
回复人: csdntoll(低调惯了) ( ) 信誉:147 2003-3-26 9:49:49 得分:0
昨天刚写的:
update picture set IsUse='1' where instr(PicPath,'_1')>0
Top
回复人: yonghengdizhen(刹那←→永恒) ( ) 信誉:112 2003-3-26 11:53:51 得分:0
下面的语句不是精华.但是却是用很多用T-SQL进行开发的同志所不了解的..
如何更新nText,Text,Image字段数据..
DECLARE @ptrval binary(16)
SELECT @ptrval = TEXTPTR(LSD_Comment)
FROM Legal_Dispute WHERE LD_Record_No=25 --得到指定记录的nText文本指针
UPDATETEXT Legal_Dispute.LSD_Comment @ptrval 0 0 N'Insert Text Content Into Old Content Before' ---将数据插入在老数据之前.
很多同志在更新nText字段的时候使用一个记录集取回ASP然后一次性用"UPDATE set fieldname='" & new content & old content & "'"的方式实现..
却不知道,sql string一次只能提交的string是有限制的,这样一来,实际的text,ntext永远也不可能存储它所支持的最大长度的数据..也远远不能达到使用nText字段的目的了..
Top