Tuesday, July 17, 2007

SQL subtotals, grandtotals

I really should google more. I sat down and thought for several hours trying to find a way to get running totals out of an SQL query. I should really give up earlier so I could have googled and found:

SQL Server: Calculating Running Totals, Subtotals and Grand Total Without a Cursor


It's got some SQL-Server-isms in there but it's generic enough that I learned the basic technique pretty quickly and implemented it in postgresql. I got my query to use running totals, and used that as a springboard to getting running balance working. I haven't yet gotten around to getting subtotals and grandtotals working, but I'm sure I'll get around to that soon, SQL use where I work is getting more sophisticated. Years ago the code used monkey-see-monkey-do and mysql style treating the database as a dumb datastore. We're on the way to something between mysql style dumb queries and doing joins in php and oracle style "do everything in the database". I think both styles have their appropriate niches, but our systems are in neither of those niches, we need to be more moderate, using SQL where it's appropriate and business logic in applications where *that's* appropriate.

No comments: