Skip to content

Instantly share code, notes, and snippets.

@z4y4ts
Created August 9, 2012 10:08
Show Gist options
  • Save z4y4ts/3302920 to your computer and use it in GitHub Desktop.
Save z4y4ts/3302920 to your computer and use it in GitHub Desktop.
SQL complex query with aggregation in web2py DAL way

Raw SQL

query = '''SELECT COALESCE(SUM(imp), 0) AS imps,
                  COALESCE(SUM(click), 0) AS clicks
           FROM logCuDate
           WHERE id=%s
               AND date >= %s
               AND date <= %s'''
res = db.executesql(query, args, as_dict=True)

web2py DAL

res = (db((db.logCuDate.id == logId) &
          (db.logCuDate.date >= dateStart) &
          (db.logCuDate.date <= dateEnd))
       .select(db.logCuDate.imp.sum().coalesce_zero().with_alias('imps'),
               db.logCuDate.click.sum().coalesce_zero().with_alias('clicks'))
       .as_list())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment