Home > Enterprise >  How to use both Count() and Min/Max in sql
How to use both Count() and Min/Max in sql

Time:02-01

I have the following table: MyTable

   name   | price
|-------------------|
|   a     |    10   |
|-------------------|
|   b     |     5   |
|-------------------|
|   a     |     7   |
|-------------------|
|   a     |     3   |
|-------------------|
|   a     |     12  |
|-------------------|
|   b     |     6   |
|-------------------|
|   c     |     2   |
|-------------------|
|   c     |     5   |
|-------------------|

I want to count the frequency of the name and need to get the max_price and min_price for each name.

The expected output is:

   name   | count   | min_price | max_price
|-------------------|----------------------|
|   a     |     4   |  3        |   12     | 
|-------------------|----------------------|
|   b     |     2   |  5        |   6      |
|-------------------|----------------------|
|   c     |     2   |  2        |   5      |
|-------------------|----------------------|

I would like to write Django ORM query. Please help me to achieve it.

CodePudding user response:

You can annotate the items with:

from django.db.models import Count, Max, Min

MyModel.objects.values('name').annotate(
    count=Count('pk'),
    min_price=Min('price'),
    max_price=Max('price')
).order_by('name')
  •  Tags:  
  • Related