SQL Flow Field Guide

Keep the intended row grain across joins

Recognize when a one to many join multiplies rows and aggregate the child data before joining it to a parent result.

What you are trying to do

A service screen needs one row per work item with its comment count and total time. Joining comments and time entries directly would multiply their rows against each other.

Work through it

  1. Read the keys in WorkItem, Comment, and TimeEntry to identify each table's row grain.
  2. Follow each aggregate CTE until it returns at most one row per WorkItemId.
  3. Trace the two LEFT JOIN operations and see why an item with no comments or time still appears.
  4. Check the final result against the expected count and effort for each task.

Check your work

The result contains exactly one row per task. Task 10 has 2 comments and 45 minutes, task 20 has 1 comment and 30 minutes, and task 30 has 0 comments and 0 minutes. The two child aggregates do not multiply each other.

Practice SQL

Open in SQL Flow
WITH WorkItem AS (
    SELECT TaskId, Title FROM (VALUES (10, N'Cache review'), (20, N'Queue alert'), (30, N'Usage report')) AS v(TaskId, Title)
), Comment AS (
    SELECT CommentId, TaskId FROM (VALUES (1, 10), (2, 10), (3, 20)) AS v(CommentId, TaskId)
), TimeEntry AS (
    SELECT EntryId, TaskId, Minutes FROM (VALUES (1, 10, 15), (2, 10, 30), (3, 20, 30)) AS v(EntryId, TaskId, Minutes)
), CommentCount AS (
    SELECT TaskId, COUNT(*) AS Comments FROM Comment GROUP BY TaskId
), TimeTotal AS (
    SELECT TaskId, SUM(Minutes) AS Minutes FROM TimeEntry GROUP BY TaskId
)
SELECT w.TaskId, w.Title, COALESCE(c.Comments, 0) AS Comments, COALESCE(t.Minutes, 0) AS Minutes
FROM WorkItem AS w
LEFT JOIN CommentCount AS c ON c.TaskId = w.TaskId
LEFT JOIN TimeTotal AS t ON t.TaskId = w.TaskId
ORDER BY w.TaskId;

Knowledge check

Commands in this lesson

Next lesson Track inserts, updates, and deletes with OUTPUT