×

sql · level 2 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Read the , then build the query one piece at a time.

Real jobs arrive as a brief: a few sentences from someone who needs answers. The librarian wants, for each member, how many loans they have had and how many books they still have out.

Build it in steps. Members is what the question is about, so it goes first. LEFT JOIN the loans, so nobody is lost, and group by member. Then add one column at a time, running as you go.

A flag inside SUM counts the books still out: loans with no returned date. Last of all, ORDER BY puts the busiest members first.

SELECT m.name, COUNT(l.id) AS loans,
  SUM(CASE WHEN l.returned IS NULL THEN 1 ELSE 0 END) AS still_out
FROM members m
LEFT JOIN loans l ON l.member_id = m.id
GROUP BY m.name
ORDER BY loans DESC, m.name;

Stuck? Go back to the last version that ran, then add one piece at a time.