This is a simple library I wrote in PHP a while ago.  It is 3rd tier library for generating SQL.  The purpose of this library was so I could write a user interface with predefined fields, where the user can select which fields to query on and it would automatically build the proper groups based on aggregate and non-aggregate fields, so the results would be what the user would expect without having to specify any groupings.