Combining aggregate functions in an (ANSI) SQL statement

Posted by morpheous on Stack Overflow See other posts from Stack Overflow or by morpheous
Published on 2010-05-15T11:23:38Z Indexed on 2010/05/15 11:24 UTC
Read the original article Hit count: 291

I have aggregate functions foo(), foobar(), fredstats(), barneystats()

I want to create a domain specific query language (DSQL) above my DB, to facilitate using using a domain language to query the DB.

The 'language' comprises of boolean expressions (or more specifically SQL like criteria) which I then 'translate' back into pure (ANSI) SQL and send to the underlying Db.

The following lines are examples of what the language statements will look like, and hopefully, it will help further clarify the concept:

**Example 1**
DQL statement: 
foobar('yellow') between 1 and 3 and fredstats('weight') > 42

Translation:
fetch all rows in an underlying table where computed values for aggregate function foobar() is between 1 and 3 AND computed value for AGG FUNC fredstats() is greater than 42


**Example 2**
DQL statement: 
fredstats('weight') < barneystats('weight') AND foo('fighter') in (9,10,11) AND foobar('green') <> 42

Translation:
Fetch all rows where the specified criteria matches


**Example 3**
DQL statement: 
foobar('green') / foobar('red') <> 42

Translation:
Fetch all rows where the specified criteria matches


**Example 4**
DQL statement: 
foobar('green') - foobar('red') >= 42

Translation:
Fetch all rows where the specified criteria matches

Given the following information:

  • The table upon which the queries above are being executed is called 'tbl'
  • table 'tbl' has the following structure (id int, name varchar(32), weight float)
  • The result set returns only the tbl.id, tbl.name and the names of the aggregate functions as columns in the result set - so for example the foobar() AGG FUNC column will be called foobar in the result set. So for example, the first DQL query will return a result set with the following columns: id, name, foobar, fredstats

Given the above, my questions then are:

  1. What would be the underlying SQL required for Example1 ?

  2. What would be the underlying SQL required for Example3 ?

  3. Given an algebraic equation comprising of AGGREGATE functions, Is there a way of generalizing the algorithm needed to generate the required ANSI SQL statement(s)?

I am using PostgreSQL as the db, but I would prefer to use ANSI SQL wherever possible.

© Stack Overflow or respective owner

Related posts about sql

Related posts about aggregate-functions