/*viết thủ tục thực hiên các yêu cầu sau, sau đó dùng thủ tục thực thi 1 trường hợp cụ thể (tham số 
tùy chọn)*/
--1.tính lương của 1 mã nhân viên (tham số)
	create proc calEmplyeeSalary(@id char(3)) as
	begin
		select HONV,TENLOT, TENNV, LUONG from NHANVIEN
		where MANV = @id
	end
	
	exec calEmplyeeSalary '009'
	
	drop proc calEmplyeeSalary
--2.xem thông tin của 1 mã nhân viên (tham số)

	create proc displayEmployeeInfo(@id char(3)) as
	begin
		select * from NHANVIEN
		where MANV = @id
	end
	
	exec displayEmployeeInfo '003'
--3.nv có lương của cao nhất

	create proc highestEmployeeSalary as
	begin
		select HONV,TENLOT, TENNV, LUONG from NHANVIEN
		where LUONG >= ( SELECT MAX(LUONG) from NHANVIEN)
	end
	
	exec highestEmployeeSalary 

--4.nhân viên có lương cao nhất của 1 tên phòng (tham số)


	create proc highestEmployeeSalaryInRoom( @tenphong nvarchar(20)) as
	begin
		select HONV,TENLOT, TENNV, LUONG, TENPHG from NHANVIEN, PHONGBAN
		where PHG = MAPHG and TENPHG = @tenphong
		group by HONV,TENLOT, TENNV, LUONG, TENPHG
		having LUONG >= ( select MAX(LUONG) from NHANVIEN, PHONGBAN
						  where PHG = MAPHG and TENPHG = @tenphong)

	end
	
	select NHANVIEN.* from NHANVIEN, PHONGBAN
	where PHG = MAPHG and TENPHG = N'Nghiên cứu '
	
	exec highestEmployeeSalaryInRoom N'Nghiên cứu '
	drop proc highestEmployeeSalaryInRoom
--5.2 nhân viên có lương cao nhất

	create proc twoHighestEmployeeSalary as
	begin
	
		select top 2 HONV,TENLOT, TENNV, LUONG from NHANVIEN
		order by LUONG desc
		 		
	end
	
	exec highestEmployeeSalary 
	
	
--6.20% nhân viên có lương cao nhất

	create proc highestEmployeeSalaryByPercent( @percent tinyint) as
	begin
	
		select top (@percent) percent HONV,TENLOT, TENNV, LUONG from NHANVIEN
		order by LUONG desc
	
	end
	
	exec highestEmployeeSalaryByPercent 20

--7.phòng ban có nhiều nv nhất

 create proc roomHasMaxEmployee as
 begin
	select COUNT(MANV), TENPHG from NHANVIEN,PHONGBAN
	where PHG = MAPHG
	group by TENPHG
	having COUNT(MANV) >= all(	select COUNT(MANV) from NHANVIEN,PHONGBAN
							where PHG = MAPHG
							group by TENPHG)
 end


--8.2 phòng ban có nhiều nhân viên nhất


 create proc twoRoomHasMaxEmployee as
 begin
	select top 2 COUNT(MANV) as fuck, TENPHG from NHANVIEN,PHONGBAN
	where PHG = MAPHG
	group by TENPHG
	order by fuck desc
 end

exec twoRoomHasMaxEmployee

--9.nv có địa chỉ ở tphcm

create proc showEmployeeByAddress( @address nvarchar(50)) as
begin

	select HONV,TENLOT, TENNV, DCHI from NHANVIEN
	where DCHI like @address
	
end

exec showEmployeeByAddress N'%Tp HCM%'


--10. nv làm việc cho 1 tên đề án

create proc showEmployeeByProjectName(@projectName nvarchar(30)) as
begin
	select HONV,TENLOT, TENNV,TENDA from NHANVIEN,DEAN
	where PHG = PHONG and TENDA = @projectName
end


exec showEmployeeByProjectName N'Cáp quang '