Opened 5 years ago
Last modified 5 years ago
#32155 closed New feature
Count() by default uses group by — at Version 2
| Reported by: | Sukhinder Mann | Owned by: | nobody |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 2.2 |
| Severity: | Normal | Keywords: | |
| Cc: | sukhinder.mann@… | Triage Stage: | Unreviewed |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description (last modified by )
I am trying to use Count() with Case to find out multiple conditional counts, and count keeps using id as default group by. I don't want it to use GROUP BY by default.
Staff.objects.filter(department__id__in=[2,3]).annotate( number_of_managers_in_UK=Sum( Case( When(position="MANAGER", location="UK", then=1), output_field=IntegerField(), ) ), number_of_directors_in_USA=Sum( Case( When(position="DIRECTOR", location="USA", then=1), output_field=IntegerField(), ) ) )
Which creates a SQL query something like this:
SELECT "staff"."id", "staff"."location", "staff"."position", "staff"."salary", "staff"."date_of_birth", -- I don't want all these other attributes as well but I can't get rid of these as well, I just need the count attributes COUNT( CASE WHEN "staff"."position" = MANAGER AND "staff"."location" = UK THEN 1 ELSE NULL END ) AS "number_of_managers_in_UK", COUNT( CASE WHEN "staff"."position" = DIRECTOR AND "staff"."location" = USA THEN 1 ELSE NULL END ) AS "number_of_directors_in_USA" FROM "staff" WHERE "staff"."department_id" IN (2, 3) GROUP BY "staff"."id"; -- This group by is unnecessary and spoils the result set
Even though Count is an Aggregator function in SQL it can be used without GROUP BY. It would be good if we can have either a parameter or something to specify whether to use group by or not instead of defaulting to GROUP BY.
Change History (2)
comment:1 by , 5 years ago
| Type: | Uncategorized → New feature |
|---|
comment:2 by , 5 years ago
| Description: | modified (diff) |
|---|
Note:
See TracTickets
for help on using tickets.