Myself getting familiar with sqlalchemy.I have a mysql query as below:
SELECT COUNT( * ) AS total, SUM( IF(sub = 'N', 1, 0 ) ) AS NotSubscribed, SUM( IF( subscription = 'A', 1, 0 ) ) AS 12Month, SUM( IF( subscription = 'HY', 1, 0 ) ) AS 6Month, SUM( IF( subscription = 'M', 1, 0 ) ) AS 1Month
FROM accounts
WHERE userID IS NOT NULL
I am trying to write a sqlalchemy version of it.
users = Table('users',metadata,autoload=True)
userInfo = users.select([func.count(users.c.userID).label('Total'),
func.sum(users.c.sub == 'N').label('NotSubscribed'),
func.sum(users.c.sub == 'A').label('12Month'),
func.sum(users.c.sub =='HY').label('6Month'),
func.sum(users.c.sub == 'M').label('1Month')]).where(users.c.userID != None).execute()
I am ending up with following error:
sqlalchemy.exc.ArgumentError: SQL expression object or string expected
Can someone help me where I am going wrong. If not let me know if there are any good tutorials about sqlalchemy apart from the documentation.
Thanks
SUM( IF(..., 1, 0))supposed to do here? Total counts for the various subscription types?SELECT subscription, COUNT(userID) FROM accounts WHERE userID IS NOT NULL GROUPBY subscription, and maketotalthe sum of the resulting rows? That query will be much lighter on the query engine too.func.sum(users.c.subscription == 'N')would not translate to theIF()statement here. You'd have to add afunc.if()too.