sql select statement

suppose we have two tables as follows

DEPARTMENT
DEP_CODE,DEP_ PERIGR
------------------
100 ,EDP
200, MARKETING
300, SALES
400, PRODUCTION

EMPLOYEES
----------------
EMPL_CODE, EMPL_NAME, EMPL_SALARY,EMPL_DEP_CODE
----------------------------------------------------------------------
1000, "AAAAAA", 2000, 100
2000, "BBBBBBB",3500, 100
3000, "CCCCCCC",3200, 200
4000, "DDDDDDD",3300, 200
5000, "BBBBBBB",3000, 300

I want to create a select statement which will return only these departments where employees have salaries  between 3150 and 3350 as well the average salary (for all the employess in each department which satisfies the criteria)
basilhs_sAsked:
Who is Participating?
 
jparulConnect With a Mentor Commented:
select Dept_Code, Dep_Perigr, average(empl_Salary) from Department D inner join Employees E on D.Dep_Code = E.Empl_Dep_Code
where E.Empl_Salary between 3150 and 3350
group by Dept_Code, Dep_Perigr
 
0
 
matthewrhoadesCommented:
Try this.

select avg(empl_salary) from employees
where empl_dep_code in (select empl_dep_code from employees where empl_salary > 3149 and empl_salary < 3351)

Open in new window

0
 
Kevin CrossChief Technology OfficerCommented:
SELECT d.DEP_CODE, d.DEP_ PERIGR
FROM Employees e
INNER JOIN Department d ON d.DEP_CODE = e.EMPL_DEP_CODE
WHERE e.EMPL_SALARY BETWEEN 3150 AND 3350
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
Kevin CrossChief Technology OfficerCommented:
And since multiple employees can have the same department, you probably want to use DISTINCT or GROUP BY statement if you want aggregate like AVG salary, etc.
SELECT d.DEP_CODE, d.DEP_ PERIGR
, COUNT(e.EMPL_CODE) As NumberMatchingSalaries
FROM Employees e
INNER JOIN Department d ON d.DEP_CODE = e.EMPL_DEP_CODE
WHERE e.EMPL_SALARY BETWEEN 3150 AND 3350
GROUP BY d.DEP_CODE, d.DEP_ PERIGR

Open in new window

0
 
matthewrhoadesCommented:
If you need the department code also:
select empl_dep_code, avg(empl_salary) from employees
where empl_dep_code in (select empl_dep_code from employees where empl_salary > 3149 and empl_salary < 3351)
group by empl_dep_code

Open in new window

0
 
Kevin CrossChief Technology OfficerCommented:
LOL, I didn't see the average salary...

No wonder everyone keeps throwing that out there.  JParul's suggestion is exactly like mine but with the average salary so that should do what you want.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.