假设我有一个像这样的 mysql 表。
| id | type | sub_type | customer |
| 1 | animal | cat | John |
| 2 | animal | dog | Marry |
| 3 | animal | fish | Marry |
| 3 | animal | bird | John |
我要做的是按客户收集数据并按子类型计算行数。动物类型有 4 个子类型(cat
、dog
、fish
、bird
),John 有两个 sub_types(cat
, bird
) 和 Marry
也有两个 sub_types(dog
, fish
)。假设我想获得 John
的结果,它应该如下所示。
[
{name='cat', count=1},
{name='dog', count=0},
{name='fish', count=0},
{name='bird', count=1}
]
当我想得到关于Marry
的结果时,它应该看起来像这样。
[
{name='cat', count=0},
{name='dog', count=1},
{name='fish', count=1},
{name='bird', count=0}
]
因此,不在数据库中的 sub_type 应该返回 count
为 0。假设我想获得 Matthew
的结果。由于没有 Matthew
的数据,结果应该如下所示。
[
{name='cat', count=0},
{name='dog', count=0},
{name='fish', count=0},
{name='bird', count=0}
]
我通常使用setdefault()
来得出结果。我的代码大概是这样的。
tmp = dict()
for row in queryset:
tmp.setdefault(row.customer, dict(cat=0, dog=0, fish=0, bird=0))
if row.sub_type == 'cat':
tmp[row.customer][row.sub_type] += 1
但是,我想知道是否有其他方法或更优雅的方法来做到这一点。
最佳答案
假设您有一个名为“people”的表,其中包含包含条目的“name”字段
name
--------
John
Mary
Mathew
上面提到的表是一个名为“pets”的表
您可以使用以下查询为每个人构建结果集
select
A.name as customer,
(select count(*) from pets where customer=A.name and sub_type='cat') as cat,
(select count(*) from pets where customer=A.name and sub_type='dog') as dog,
(select count(*) from pets where customer=A.name and sub_type='fish') as fish,
(select count(*) from pets where customer=A.name and sub_type='bird') as bird
from people A
结果如下所示
customer cat dog fish bird
John 1 0 0 1
Marry 0 1 1 0
Mathew 0 0 0 0
添加额外的 where 子句并过滤我的姓名或提供 一次性汇总结果。
关于python - 即使数据不存在,也收集数据、计数并返回字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50538774/