简体   繁体   中英

Sqlalchemy groupby how do I know which value belongs to which group?

Say I have the following data:

Clicks           Device
-------------------------
  1              Mobile
  2              Desktop
  1              Tablet
  1              Mobile       
 ..                ..

I am querying the table as follows:

q = db_session.query(func.count(Website.Clicks)).group_by(Website.Device)


for a in q:
print(a)

The result is:

2
2
1

My question is how do I know which value belongs to which device? So for example how can I query a or output the following:

Mobile 2
Desktop 2
Tablet 1

Your query only projects the count of Website Clicks, so that's all you're getting. Add the Devices to the projection:

q = db_session.query(Website.Device, func.count(Website.Clicks)).group_by(Website.Device)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM