python - 即使数据不存在,也收集数据、计数并返回字典列表

标签 python mysql count

假设我有一个像这样的 mysql 表。

| id | type        | sub_type | customer    |
|  1 | animal      | cat      | John        |
|  2 | animal      | dog      | Marry       |
|  3 | animal      | fish     | Marry       |
|  3 | animal      | bird     | John        |

我要做的是按客户收集数据并按子类型计算行数。动物类型有 4 个子类型(catdogfishbird),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/

相关文章:

mysql - 计数 'HAVING',其中所有记录都有列 = ''

MySQL select - 按组获取计数

mysql - 从行中的金额中获取总数 MySQL PHP

python - 如何使用 OpenCV 理解 Python 中的头部姿势估计角度?

python - 字符串中包含换行符(\n),如何用正则表达式将\n替换为\n?

php - SQL 分组不按预期工作

php - Laravel:在迁移过程中重命名表字段而不删除数据

javascript - 使用 Python Flask 自定义 Stripe Checkout

python - PIL - 绘制文本并保存

php - 我应该加密整个数据库,还是只加密其中的字段?