Skip to content

Instantly share code, notes, and snippets.

@JC5
Created December 1, 2022 05:29
Show Gist options
  • Save JC5/760650caab05065bf52293eb2f2d0a92 to your computer and use it in GitHub Desktop.
Save JC5/760650caab05065bf52293eb2f2d0a92 to your computer and use it in GitHub Desktop.
Sort accounts by usage and amount

This is MySQL but should work as expected in other databases.

 SELECT COUNT(transactions.id)   AS transaction_count,
       SUM(transactions.amount)  AS total,
       accounts.name
FROM   transactions
       LEFT JOIN transaction_journals
              ON transactions.transaction_journal_id = transaction_journals.id
       LEFT JOIN accounts
              ON transactions.account_id = accounts.id
       LEFT JOIN transaction_types
              ON transaction_journals.transaction_type_id = transaction_types.id
WHERE  transaction_journals.date >= "2022-01-01"
       AND transaction_journals.date <= "2022-12-31"
       AND transaction_types.type = "Withdrawal"
       AND amount > 0
GROUP  BY accounts.name
ORDER  BY transaction_count ASC,
          total DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment