AtkinsSJ

SQL fun

Feb 5th, 2015
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.24 KB | None | 0 0
  1. -- Everything about Rounds!
  2. -- Name, customer count, due customer count, and total customer debt
  3. SELECT rounds._id, rounds.name,
  4.     COUNT(customers._id) AS customer_count,
  5.     IFNULL(due_customers.customers_due,0) AS customers_due,
  6.     IFNULL(round_debts.debt,0) AS total_debt
  7. FROM rounds
  8. LEFT JOIN customers ON customers.round_id = rounds._id
  9. LEFT JOIN (
  10.     -- Create an imaginary table of round_id -> customers_due
  11.     SELECT customers.round_id, COUNT(customers._id) AS customers_due
  12.     FROM customers
  13.     WHERE (
  14.         -- Returns 1 if there are no visits within *frequency* days, otherwise 0
  15.         SELECT 1 - COUNT(visits._id)
  16.         FROM visits
  17.         WHERE visits.customer_id = customers._id
  18.             AND (visits.DATE + customers.frequency*86400) > UNIX_TIMESTAMP()
  19.         ORDER BY visits.DATE DESC
  20.         LIMIT 1
  21.     ) = 1
  22.     GROUP BY customers.round_id
  23. ) AS due_customers ON due_customers.round_id = rounds._id
  24. LEFT JOIN (
  25.     -- Sum debt for each round
  26.     SELECT customers.round_id, SUM(visits.charge) AS debt
  27.     FROM visits
  28.     LEFT JOIN customers ON customers._id = visits.customer_id
  29.     WHERE visits.paid = 0
  30.     GROUP BY customers.round_id
  31. ) AS round_debts ON round_debts.round_id = rounds._id
  32. GROUP BY rounds._id
Advertisement
Add Comment
Please, Sign In to add comment