经典数据库题

一、按部门名称查询出员工的人数大于等于100的语句.(员工:emp_employee, 部门名称: department,员工姓名chnalias.)
SELECT departrnent FROM emp_employee GROUP BY departrnent HAVING COUNT(*) >=100

二、把员工的姓名、性别和年龄显示出来。(员工表emp_employee, 员工姓名:chnalias,年龄age,性别:gender。性别表:pub_gendar_info,性别名称:smpalias,与员工表的性别关
SELECT e.chnalias,g.smpalias,e.age FROM emp_employee e INNERJOIN pub_gendar g ONe.gendar = g.smpalias

三、当部门表的名称为空时,用0来代替。(部门表org_department 名称smpalias)
SELECT (CASE WHEN smpalias=’null’ THEN ’0′ ELSE smpalias END) AS ‘部门名称’ FROM org_departmen
Select replace(smpalias,’null’,’0’) fromorg_department

四、删除员工表中的姓名重复的数据,只保留重复数据中的一条数据。(员工表emp_employee,员工姓名:chnalias)
DELETE FROM emp_employee WHERE id NOT IN ( SELECT MAX(id) AS id FROM emp_employee GROUP BY chnalias )

五、有三个部门:1人力资源部,2信息中心,3.安全监察部分别把这个三个部门的人员统计出来。要求用sql语句一行来实现(员工表emp_employee,员工姓名:chnalias,员工表对应的部门id:department.。部门表:org_departmen。部门表的字段:部门名称smpalias,部门主键:id)部门表的id=员工表的department
显示的结果应该是:
人力资源部 信息中心 安全监察部
10 20 30
SELECT SUM (f.s1) AS ‘人力资源部’,SUM (f.s2)AS ‘信息中心’, SUM (f.s3)AS ‘信息中心’
from
(
SELECT(CASE WHEN d.smpalias=’人力资源部’ THEN SUM(e.Departid) END) AS s1,
(CASE WHEN d.smpalias=’信息中心’ THEN SUM(e.Departid) END) AS s2,
(CASE WHEN d.smpalias=’安全监察部’ THEN SUM(e.Departid) END) AS s3
FROM emp_employee e INNER JOIN org_departmen d ONe.departId=d.id
GROUP BY d.smpalias ) f

六、查询出差表中的每个员工最近的出差时间和员工姓名(出差表emp_travel,员工姓名chnalias,出差时间godate)
SELECT chnalias,godate FROM emp_travel ORDERBY godate DESC

七、请写一个存储过程,把emp_employee表中的chnalias这个字段的名称更新为’您好’。
CREATE PROC proc_updateemp
AS
UPDATE FROM emp_employee SET chnalias = ‘您好’
GO
EXEC proc_updateemp

八、请写一个函数,用来实现把一个字段的内容横向显示出来。(表pub_codeitem_inf,代码组字段groupcode,名称字段:smpalias.每行内容用逗号分开)
create function dbo.f_str(@id int) return varchar(100)
as
begin
declare @str varchar(1000)
set @str=”;
select @str=@str+’,'+cast(smpalias as varchar) frompub_codeitem_inf where groupcode=@id
set @str=right(@str,len(@str)-1)
return @str
end
go
–调用函数
select groupcode,smplias=dbo.f_str(groupcode) from pub_codeitem_inf groupby groupcode

九、请写一个游标用来把表中的数据显示出来(表emp_employee,显示姓名chnalias和单位company)
Create proc employee
@company varchar(50)=’’
@chnalias varchar(50)=’’
as
declare @curList
set @curList= cursor for
select chnalias,company fromemp_employee
open @curList
fetch next from @curList into @chnalias,@company
while(@@fetch status=0)
begin
print @chnalias+@company
fetch next from @curList into @chnalias,@company
end
close @curList
deallocate @curList

十、请用sql语句写一个从1减到100的语句出来。
Declare @star int ,@sum int
Select @star =1,@sum=0
While(@star<=100)
Begin
Set @sum=@sum – @star
Set @star=@star + 1
End
Select @sum

posted on 2013-12-30 18:42  wcq  阅读(317)  评论(0编辑  收藏  举报

导航