Data Engineering

SQL Window Functions: Keep Each Row and Add a Team Total

SoftwareJobs.io editorial24 November 20262 min read

Sometimes you need individual rows and a total beside each one. A SQL window function can calculate across related rows while keeping the row detail. Here is a small example you can practise before a Malta data interview.

Use a tiny dataset

Imagine a work_log table with three rows: Support, Ada, 2 hours; Support, Ben, 3 hours; and Data, Cara, 4 hours. These are invented names and values for learning.

SELECT team, person, hours,
       SUM(hours) OVER (PARTITION BY team) AS team_hours
FROM work_log;

Ada’s row shows 2 individual hours and a team total of 5. Ben’s row shows 3 and 5. Cara’s row shows 4 and 4. There are still three result rows. A normal grouped query by team would instead produce one row per team. The PostgreSQL tutorial explains this distinction.

Make a prediction before running it

Add a fourth invented row: Support, Dan, 1 hour. Write down the expected team total for each Support row. It should now be 6, while each person keeps their own hours. This exercise checks whether you understand the partition rather than only recognising OVER in a query.

Avoid adding the repeated total

The team total is repeated for the team’s rows. Adding that displayed column across every row would count it repeatedly. Decide what one output row represents before using it in a report.

For an interview, explain why you need both detail and a total. That business reason makes the technical choice easier to follow.

Sources and further reading

Browse current technology jobs in Malta →

PUT YOUR IDEAS INTO ACTION

What’s your next move?

Explore software, cloud and data roles that fit your skills and ambitions.

Explore opportunities
KEEP EXPLORING

More ideas for your next chapter