Python Practice › SQLite Programs › Program 10

Group by

EasySQLite Programs · 10 of 20

Write a Python program to count employees and average salary per department.

Advertisement
Output
('Dev', 2, 64000.0)
('QA', 2, 50000.0)

Approach

  1. GROUP BY dept.

Solution

Python
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.

More sqlite programs

← All 20 SQLite Programs

Leave a Comment