Python Practice › SQLite Programs › Program 10
Group by
Write a Python program to count employees and average salary per department.
Output
('Dev', 2, 64000.0)
('QA', 2, 50000.0)Approach
GROUP BY dept.
Solution
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE emp (name TEXT, dept TEXT, salary INTEGER)")conn.executemany("INSERT INTO emp VALUES (?, ?, ?)", [("Asha", "QA", 52000), ("Ravi", "Dev", 61000), ("Meena", "QA", 48000), ("Sara", "Dev", 67000)])for row in conn.execute("SELECT dept, COUNT(*), AVG(salary) FROM emp GROUP BY dept ORDER BY dept"): print(row)Output
('Dev', 2, 64000.0)
('QA', 2, 50000.0)Learn the concept
New to this topic? Read the lesson, then come back.