Average Salary By Department

Easy

Description

Write a SQL query to find the average salary for each department. Return department and average salary (rounded to integer), ordered by average salary descending. **Output columns (in order):** department, avg_salary

Table:employees
ColumnType
idINT
nameTEXT
salaryINT
departmentTEXT

Examples

Input:CREATE TABLE employees (id INT, name TEXT, salary INT, department TEXT); INSERT INTO employees VALUES (1, 'Alice', 50000, 'Engineering'), (2, 'Bob', 60000, 'Marketing'), (3, 'Charlie', 55000, 'Engineering');
Output:Marketing|60000 Engineering|52500
Explanation:

Marketing has Bob with salary 60000 (average 60000). Engineering has Alice (50000) and Charlie (55000), averaging (50000+55000)/2 = 52500.

Input:CREATE TABLE employees (id INT, name TEXT, salary INT, department TEXT); INSERT INTO employees VALUES (1, 'David', 75000, 'Sales'), (2, 'Emma', 45000, 'HR'), (3, 'Frank', 80000, 'Sales'), (4, 'Grace', 50000, 'HR'), (5, 'Henry', 85000, 'Sales'), (6, 'Iris', 48000, 'HR');
Output:Sales|80000 HR|47667
Explanation:

Sales department has 3 employees with salaries 75000, 80000, 85000, averaging to 80000. HR department has 3 employees with salaries 45000, 50000, 48000, averaging to 47666.67 which rounds to 47667.

Input:CREATE TABLE employees (id INT, name TEXT, salary INT, department TEXT); INSERT INTO employees VALUES (1, 'John', 120000, 'Finance'), (2, 'Kate', 95000, 'IT'), (3, 'Liam', 98000, 'IT'), (4, 'Maya', 110000, 'Finance'), (5, 'Noah', 100000, 'Operations');
Output:Finance|115000 Operations|100000 IT|96500
Explanation:

Finance has 2 employees averaging (120000+110000)/2 = 115000. Operations has 1 employee with salary 100000. IT has 2 employees averaging (95000+98000)/2 = 96500. Results ordered by average salary descending.

Constraints

  • Use AVG() and GROUP BY

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!