【网学网提醒】:文章导读:在新的一年中,各位网友都进入紧张的学习或是工作阶段。网学会员整理了SQL语法之高级查询的相关内容供大家参考,祝大家在新的一年里工作和学习顺利!
SQL语法之高级查询
动态sql语句基本语法
1:普通SQL语句可以用Exec执行
eg:Select*fromtableName
Exec('select*fromtableName')
Execsp_executesqlN'select*fromtableName'--请注意字符串前一定要加N
2:字段名,表名,数据库名之类作为变量时,必须用动态SQL
declare@fnamevarchar(20)
set@fname='FiledName'
Select@fnamefromtableName--错误,不会提示错误,但结果为固定值FiledName,并非所要。
Exec('select'+@fname+'fromtableName')--请注意加号前后的单引号的边上加空格
当然将字符串改成变量的形式也可
declare@fnamevarchar(20)
set@fname='FiledName'--设置字段名
declare@svarchar(1000)
set@s='select'+@fname+'fromtableName'
Exec(@s)--成功
execsp_executesql@s--此句会报错
declare@sNvarchar(1000)--注意此处改为nvarchar(1000)
set@s='select'+@fname+'fromtableName'
Exec(@s)--成功
execsp_executesql@s--此句正确
3.输出参数
declare@numint,
@sqlsnvarchar(4000)
set@sqls='selectcount(*)fromtableName'
exec(@sqls)
--如何将exec执行结果放入变量中?
declare@numint,
@sqlsnvarchar(4000)
set@sqls='select@a=count(*)fromtableName'
execsp_executesql@sqls,N'@aintoutput',@numoutput
select@num
select*fromsysobjectswherextype='tr'--返回库中触发器
select*fromsysobjectswherextype='U'--返回库中用户表
1.日期算當月天數:
selectDay(dateadd(day,-1,convert(datetime,convert(char(07),dateadd(m,1,getdate()),120)+'-01')))
select32-Day(getdate()+(32-Day(getdate())))
2.簡單的分割字串:
用'unionallselect'replace'分割符'
OrderBy可以指定列序而不用指定列名,在下面的例子里说明它的用处(注意,第三列未指定别名)
Selecta.ID,a.Name,(SelectCount(*)FromTableBbWherea.ID=b.PID)FromTableAaOrderBy3
--修改用户数据库的排序规则
aterdatabasedbnamecollateSQL_Latin1_General_CP1_CI_AS
--修改字段的排序规则
altertableaaltercolumnc2varchar(50)collateSQL_Latin1_General_CP1_CI_AS
--按姓氏笔画排序
select*from表名orderby列名CollateChinese_PRC_Stroke_ci_as
--按拼音首字母排序
select*from表名orderby列名CollateChinese_PRC_CS_AS_KS_WS
--查找一个Server下含有某个表名的数据库名字
EXECsp_msforeachdb'
USE[?]
IFOBJECT_ID(N''表名'')ISNOTNULL
PRINTN''?'''
--查询所有表名、字段名及字段描述
select
表名=object_name(id),
列名=col_name(object_id(object_name(id)),smallid),
描述=value
fromsysproperties
--查询所有表的记录数明细
--方法(1)
select
a.name,b.rows
from
sysobjectsa,sysindexesb
where
a.name=b.nameanda.type='u'
--方法(2)
sp_msforeachtable'select''?''as''表名'',(selectsum(1)from?)as''记录数'''
--复制表(表结构)
--方法(1)
select*into
Employee_bakfromEmployeewhere1<>1
--方法(2)
selecttop0*intoEmployee_bakfromEmployee
--方法(3)
--企业管理器中的右键表-->复制,然后在查询分析器中粘贴查看SQL语句
--判断两字符是否完全(区分大小写)相等(如何判断字符的大小写)
declare@vnvarchar(10)
declare@pnvarchar(10)
set@v='NIPSAN'
ifcast(@vasvarbinary)=cast(@pasvarbinary)
printN'相等'
else
printN'不等'
--得到数据库中所有表的空间/记录情况
execsp_MSForEachTable
@precommand=N'
createtable##(
idintidentity,
表名sysname,
字段数int,
记录数int,
保留空间Nvarchar(10),
使用空间varchar(10),
索引使用空间varchar(10),
未用空间varchar(10))',
@command1=N'insert##(表名,记录数,保留空间,使用空间,索引使用空间,未用空间)execsp_spaceused''?''
update##set字段数=(selectcount(*)fromsyscolumnswhereid=object_id(''?''))
whereid=scope_identity()',@postcommand=N'select*from##orderbyiddroptable##'
--查看硬盘分区:
EXECmaster..xp_fixeddrives
--OrderBy的一个小技巧
/*
OrderBy可以指定列序而不用指定列名,在下面的例子里说明它的用处(注意,第三列未指定别名)
Selecta.ID,a.Name,(SelectCount(*)FromTableBbWherea.ID=b.PID)FromTableAaOrderBy3
*/
表结构新
SELECT
表名=casewhena.colorder=1thend.nameelse''end,
表说明=casewhena.colorder=1thenisnull(f.value,'')else''end,
字段序号=a.colorder,
字段名=a.name,
标识=casewhenCOLUMNPROPERTY(a.id,a.name,'IsIdentity')=1then'√'else''end,
主键=casewhenexists(SELECT1FROMsysobjectswherextype='PK'andparent_obj=a.idandnamein(
SELECTnameFROMsysindexesWHEREindidin(
SELECTindidFROMsysindexkeysWHEREid=a.idANDcolid=a.colid
)))then'√'else''end,
类型=b.name,
占用字节数=a.length,
长度=COLUMNPROPERTY(a.id,a.name,'PRECISION'),
小数位数=isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
允许空=casewhena.isnullable=1then'√'else''end,
默认值=isnull(e.text,''),
字段说明=isnull(g.[value],''),
索引名称=isnull(h.索引名称,''),
索引顺序=isnull(h.排序,'')
FROMsyscolumnsa
leftjoinsystypesbona.xtype=b.xusertype
innerjoinsysobjectsdona.id=d.idandd.xtype='U'andd.status>=0
leftjoinsyscommentseona.cdefault=e.id
leftjoinsyspropertiesgona.id=g.idanda.colid=g.smallid
leftjoinsyspropertiesfond.id=f.idandf.smallid=0
leftjoin(--这部分是索引信息,如果要显示索引与表及字段的对应关系,可以只要此部分
select索引名称=a.name,c.id,d.colid
,排序=caseindexkey_property(c.id,b.indid,b.keyno,'isdescending')
when1then'降序'when0then'升序'end
fromsysindexesa
joinsysindexkeysbona.id=b.idanda.indid=b.indid
join(--这里的作用是有多个索引时,取索引号最小的那个
selectid,colid,indid=min(indid)fromsysind
exkeys
groupbyid,colid)b1onb.id=b1.idandb.colid=b1.colidandb.indid=b1.indid
joinsysobjectsconb.id=c.idandc.xtype='U'andc.status>=0
joinsyscolumnsdonb.id=d.idandb.colid=d.colid
wherea.indidnotin(0,255)
)hona.id=h.idanda.colid=h.colid
--whered.name='要查询的表'--如果只查询指定表,加上此条件
orderbya.id,a.colorder
--索引信息
--索引信息
select索引名称=casewhenb.keyno=1thena.nameelse''end
,表名=casewhenb.keyno=1thenc.nameelse''end
,列名=d.name
,排序=caseindexkey_property(c.id,b.indid,b.keyno,'isdescending')
when1then'降序'when0then'升序'end
,聚集=INDEXPROPERTY(c.id,a.name,'IsClustered')
,唯一=caseINDEXPROPERTY(c.id,a.name,'IsUnique')
when0then'非唯一'
when1thencasewhene.idisnullthen'唯一索引'else'唯一约束'end
end
,e.name
,填充因子=a.OrigFillFactor
fromsysindexesa
joinsysindexkeysbona.id=b.idanda.indid=b.indid
--join(--这里的作用是有多个索引时,取索引号最小的那个
--selectid,colid,indid=min(indid)fromsysindexkeys
--groupbyid,colid)b1onb.id=b1.idandb.colid=b1.colidandb.indid=b1.indid
joinsysobjectsconb.id=c.idandc.xtype='U'andc.status>=0
joinsyscolumnsdonb.id=d.idandb.colid=d.colid
leftjoinsysobjectseonb.indid=e.idande.xtype='UQ'
wherea.indidnotin(0,255)
orderbyc.name,a.name
找出表中某一列相同的数据行
select*fromtablewhere(columnin(selectcolumnfromtablegroupbycolumnhavingcount(*)>1)
--1、查找员工的编号、、部门和出生日期,如果出生日期为空值,
--显示日期不详,并按部门排序输出,日期格式为yyyy-mm-dd。
selectemp_no,emp_name,dept,
isnull(convert(char(10),birthday,120),'日期不详')birthday
fromemployee
orderbydept
--2、查找与喻自强在同一个单位的员工、性别、部门和职称
selectemp_no,emp_name,dept,title
fromemployee
whereemp_name<>'喻自强'anddeptin
(selectdeptfromemployee
whereemp_name='喻自强')
--3、按部门进行汇总,统计每个部门的总工资
selectdept,sum(salary)
fromemployee
groupbydept
--4、查找商品名称为14寸显示器商品的销售情况,
--显示该商品的编号、销售数量、单价和金额
selecta.prod_id,qty,unit_price,unit_price*qtytotprice
fromsale_itema,productb
wherea.prod_id=b.prod_idandprod_name='14寸显示器'
--5、在销售明细表中按产品编号进行汇总,统计每种产品的销售数量和金额
selectprod_id,sum(qty)totqty,sum(qty*unit_price)totprice
fromsale_item
groupbyprod_id
--6、使用convert函数按客户编号统计每个客户1996年的订单总金额
selectcust_id,sum(tot_amt)totprice
fromsales
whereconvert(char(4),order_date,120)='1996'
groupbycust_id
--7、查找有销售记录的客户编号、名称和订单总额
selecta.cust_id,cust_name,sum(tot_a
mt)totprice
fromcustomera,salesb
wherea.cust_id=b.cust_id
groupbya.cust_id,cust_name
--8、查找在1997年中有销售记录的客户编号、名称和订单总额
selecta.cust_id,cust_name,sum(tot_amt)totprice
fromcustomera,salesb
wherea.cust_id=b.cust_idandconvert(char(4),order_date,120)='1997'
groupbya.cust_id,cust_name
--9、查找一次销售最大的销售记录
selectorder_no,cust_id,sale_id,tot_amt
fromsales
wheretot_amt=
(selectmax(tot_amt)
fromsales)
--10、查找至少有3次销售的业务员名单和销售日期
selectemp_name,order_date
fromemployeea,salesb
whereemp_no=sale_idanda.emp_noin
(selectsale_id
fromsales
groupbysale_id
havingcount(*)>=3)
orderbyemp_name
--11、用存在量词查找没有订货记录的客户名称
selectcust_name
fromcustomera
wherenotexists
(select*
fromsalesb
wherea.cust_id=b.cust_id)
--12、使用左外连接查找每个客户的客户编号、名称、订货日期、订单金额
--订货日期不要显示时间,日期格式为yyyy-mm-dd
--按客户编号排序,同一客户再按订单降序排序输出
selecta.cust_id,cust_name,convert(char(10),order_date,120),tot_amt
fromcustomeraleftouterjoinsalesbona.cust_id=b.cust_id
orderbya.cust_id,tot_amtdesc
--13、查找16MDRAM的销售情况,要求显示相应的销售员的、
--性别,销售日期、销售数量和金额,其中性别用男、女表示
selectemp_name,性别=casea.sexwhen'm'then'男'
when'f'then'女'
else'未'
end,
销售日期=isnull(convert(char(10),c.order_date,120),'日期不详'),
qty数量,qty*unit_priceas金额
fromemployeea,salesb,sale_itemc,productd
whered.prod_name='16MDRAM'andd.pro_id=c.prod_idand
a.emp_no=b.sale_idandb.order_no=c.order_no
--14、查找每个人的销售记录,要求显示销售员的编号、、性别、
--产品名称、数量、单价、金额和销售日期
selectemp_no编号,emp_name,性别=casea.sexwhen'm'then'男'
when'f'then'女'
else'未'
end,
prod_name产品名称,销售日期=isnull(convert(char(10),c.order_date,120),'日期不详'),
qty数量,qty*unit_priceas金额
fromemployeealeftouterjoinsalesbona.emp_no=b.sale_id,sale_itemc,productd
whered.pro_id=c.prod_idandb.order_no=c.order_no
--15、查找销售金额最大的客户名称和总货款
selectcust_name,d.cust_sum
fromcustomera,
(selectcust_id,cust_sum
from(selectcust_id,sum(tot_amt)ascust_sum
fromsales
groupbycust_id)b
whereb.cust_sum=
(sel
ectmax(cust_sum)
from(selectcust_id,sum(tot_amt)ascust_sum
fromsales
groupbycust_id)c)
)d
wherea.cust_id=d.cust_id
--16、查找销售总额少于1000元的销售员编号、和销售额
selectemp_no,emp_name,d.sale_sum
fromemployeea,
(selectsale_id,sale_sum
from(selectsale_id,sum(tot_amt)assale_sum
fromsales
groupbysale_id)b
whereb.sale_sum<1000
)d
wherea.emp_no=d.sale_id
--17、查找至少销售了3种商品的客户编号、客户名称、商品编号、商品名称、数量和金额
selecta.cust_id,cust_name,b.prod_id,prod_name,d.qty,d.qty*d.unit_price
fromcustomera,productb,salesc,sale_itemd
wherea.cust_id=c.cust_idandd.prod_id=b.prod_idand
c.order_no=d.order_noanda.cust_idin(
selectcust_id
from(selectcust_id,count(distinctprod_id)prodid
from(selectcust_id,prod_id
fromsalese,sale_itemf
wheree.order_no=f.order_no)g
groupbycust_id
havingcount(distinctprod_id)>=3)h)
--18、查找至少与世界技术开发公司销售相同的客户编号、名称和商品编号、商品名称、数量和金额
selecta.cust_id,cust_name,d.prod_id,prod_name,qty,qty*unit_price
fromcustomera,productb,salesc,sale_itemd
wherea.cust_id=c.cust_idandd.prod_id=b.prod_idand
c.order_no=d.order_noandnotexists
(selectf.*
fromcustomerx,salese,sale_itemf
wherecust_name='世界技术开发公司'andx.cust_id=e.cust_idand
e.order_no=f.order_noandnotexists
(selectg.*
fromsale_itemg,salesh
whereg.prod_id=f.prod_idandg.order_no=h.order_noand
h.cust_id=a.cust_id)
)
19、查找表中所有姓刘的职工的工号,部门,薪水
selectemp_no,emp_name,dept,salary
fromemployee
whereemp_namelike'刘%'
20、查找所有定单金额高于20000的所有客户编号
selectcust_id
fromsales
wheretot_amt>20000
21、统计表中员工的薪水在40000-60000之间的人数
selectcount(*)as人数
fromemployee
wheresalarybetween40000and60000
22、查询表中的同一部门的职工的平均工资,但只查询"住址"是"上海市"的员工
selectavg(salary)avg_sal,dept
fromemployee
whereaddrlike'上海市%'
groupbydept
23、将表中住址为"上海市"的员工住址改为"北京市"
updateemployee
setaddrlike'北京市'
whereaddrlike'上海市'
24、查找业务部或会计部的女员工的基本信息。
selectemp_no,emp_name,dept
fromemployee
wheresex='F'anddeptin('业务','会计')
25、显示每种产品的销售金额总和,并依销售金额由大到小输出。
selectprod_id,sum(qty*unit_price)
fromsale_item
groupbyprod_id
order
bysum(qty*unit_price)desc
26、选取编号界于‘C0001’和‘C0004’的客户编号、客户名称、客户地址。
selectCUST_ID,cust_name,addr
fromcustomer
wherecust_idbetween'C0001'AND'C0004'
27、计算出一共销售了几种产品。
selectcount(distinctprod_id)as'共销售产品数'
fromsale_item
28、将业务部员工的薪水上调3%。
updateemployee
setsalary=salary*1.03
wheredept='业务'
29、由employee表中查找出薪水最低的员工信息。
select*
fromemployee
wheresalary=
(selectmin(salary)
fromemployee)
30、使用join查询客户为"客户丙"所购货物的"客户名称","定单金额","定货日期","电话号码"
selecta.cust_id,b.tot_amt,b.order_date,a.tel_no
fromcustomerajoinsalesb
ona.cust_id=b.cust_idandcust_namelike'客户丙'
31、由sales表中查找出订单金额大于“E0013业务员在1996/10/15这天所接每一张订单的金额”的所有订单。
select*
fromsales
wheretot_amt>all
(selecttot_amt
fromsales
wheresale_id='E0013'andorder_date='1996/10/15')
orderbytot_amt
32、计算'P0001'产品的平均销售单价
selectavg(unit_price)
fromsale_item
whereprod_id='P0001'
33、找出公司女员工所接的定单
selectsale_id,tot_amt
fromsales
wheresale_idin
(selectsale_idfromemployee
wheresex='F')
34、找出同一天进入公司服务的员工
selecta.emp_no,a.emp_name,a.date_hired
fromemployeea
joinemployeeb
on(a.emp_no!=b.emp_noanda.date_hired=b.date_hired)
orderbya.date_hired
35、找出目前业绩超过232000元的员工编号和。
selectemp_no,emp_name
fromemployee
whereemp_noin
(selectsale_id
fromsales
groupbysale_id
havingsum(tot_amt)<232000)
36、查询出employee表中所有女职工的平均工资和住址在"上海市"的所有女职工的平均工资
selectavg(salary)
fromemployee
wheresexlike'f'
union
selectavg(salary)
fromemployee
wheresexlike'f'andaddrlike'上海市%'
37、在employee表中查询薪水超过员工平均薪水的员工信息。
Select*fromemployeewheresalary>(selectavg(salary)fromemployee)
38、找出目前销售业绩超过40000元的业务员编号及销售业绩,并按销售业绩从大到小排序。
Selectsale_id,sum(tot_amt)
fromsales
groupbysale_id
havingsum(tot_amt)>40000
orderbysum(tot_amt)desc
39、找出公司男业务员所接且订单金额超过2000元的订单号及订单金额。
Selectorder_no,tot_amt
Fromsales,employee
Wheresale_id=emp_noandsex='M'andtot_amt>2000
40、查询sales表中订单金额最高的订单号及订单金额。
Selectorder_no,tot_amtfromsaleswheretot_amt=(selectmax(tot_amt)fromsales)
41、查询在每张订单中订购金额超过24000元的客户名及其地址。
Selectcust_name,addrfromcustomera,salesbwherea.cust_id=b.cust_idandtot_amt>24000
42、
求出每位客户的总订购金额,显示出客户号及总订购金额,并按总订购金额降序排列。
Selectcust_id,sum(tot_amt)fromsales
Groupbycust_id
Orderbysum(tot_amt)desc
43、求每位客户订购的每种产品的总数量及平均单价,并按客户号,产品号从小到大排列。
Selectcust_id,prod_id,sum(qty),sum(qty*unit_price)/sum(qty)
Fromsalesa,sale_itemb
Wherea.order_no=b.order_no
Groupbycust_id,prod_id
Orderbycust_id,prod_id
44、查询订购了三种以上产品的订单号。
Selectorder_nofromsale_item
Groupbyorder_no
Havingcount(*)>3
45、查询订购的产品至少包含了订单10003中所订购产品的订单。
Selectdistinctorder_no
Fromsale_itema
Whereorder_no<>'10003'andnotexists(
Select*fromsale_itembwhereorder_no='10003'andnotexists
(select*fromsale_itemcwherec.order_no=a.order_noandc.prod_id=b.prod_id))
46、在sales表中查找出订单金额大于“E0013业务员在1996/11/10这天所接每一张订单的金额”的所有订单,并显示承接这些订单的业务员和该订单的金额。
Selectsale_id,tot_amtfromsales
wheretot_amt>all(selecttot_amtfromsaleswheresale_id='E0013'andorder_date='1996/11/10')
47、查询末承接业务的员工的信息。
Select*
Fromemployeea
Wherenotexists
(select*fromsalesbwherea.emp_no=b.sale_id)
48、查询来自上海市的客户的,电话、订单号及订单金额。
Selectcust_name,tel_no,order_no,tot_amt
Fromcustomera,salesb
Wherea.cust_id=b.cust_idandaddr='上海市'
49、查询每位业务员各个月的业绩,并按业务员编号、月份降序排序。
Selectsale_id,month(order_date),sum(tot_amt)
fromsales
groupbysale_id,month(order_date)
orderbysale_id,month(order_date)desc
50、求每种产品的总销售数量及总销售金额,要求显示出产品编号、产品名称,总数量及总金额,并按产品号从小到大排列。
Selecta.prod_id,prod_name,sum(qty),sum(qty*unit_price)
Fromsale_itema,productb
Wherea.prod_id=b.prod_id
Groupbya.prod_id,prod_name
Orderbya.prod_id
51、查询总订购金额超过’C0002’客户的总订购金额的客户号,客户名及其住址。
Selectcust_id,cust_name,addr
Fromcustomer
Wherecust_idin(selectcust_idfromsales
Groupbycust_id
Havingsum(tot_amt)>
(Selectsum(tot_amt)fromsaleswherecust_id='C0002'))
52、查询业绩最好的的业务员号、业务员名及其总销售金额。
selectemp_no,emp_name,sum(tot_amt)
fromemployeea,salesb
wherea.emp_no=b.sale_id
groupbyemp_no,emp_name
havingsum(tot_amt)=
(selectmax(totamt)
from(selectsale_id,sum(tot_amt)totamt
fromsales
groupbysale_id)c)
53、查询每位客户所订购的每种产品的详细清单,要求显示出客户号,客户名,产品号,产品名,数
量及单价。
selecta.cust_id,cust_name,c.prod_id,prod_name,qty,unit_price
fromcustomera,salesb,sale_itemc,productd
wherea.cust_id=b.cust_idandb.order_no=c.order_noandc.prod_id=d.prod_id
54、求各部门的平均薪水,要求按平均薪水从小到大排序。
selectdept,avg(salary)fromemployeegroupbydeptorderbyavg(salary)