Postgresql - 获取计数和结果

标签 postgresql count aggregate-functions knex.js

我有 2 张 table

cars
|id|name|car_type_id|

car_types
|id|name|
对于汽车来说,

car_type_id 可以为 null。

我想查询我的数据库,以便获得汽车类型列表,以及每种car_type 的汽车数量。车型为null的车型可以为null。

我希望这是清楚的。但欢迎任何建议。

所以我希望找回类似的东西

car_type      | count
car type 1    | 3
car type 2    | 4
uncategorized | 12

编辑: 所以我可以使用获取类型及其总数

select 
car_type.id,
car_type.name,
(SELECT COUNT(*) FROM cars 
 WHERE cars.car_type_id = car_type.id) as tot
from car_type

但这并没有给我所有 car_type_id 为 null 的汽车

最佳答案

使用从 carscar_types 的外部(即 left)连接,但将 'uncategorized' 指定为没有连接的 car_type 名称。将其与反向联接结合起来,过滤出匹配的行。

select 
    coalesce(car_types.name, 'uncategorized') as car_type,
    count(*) as tot
from cars
left join car_types on cars.car_type_id = car_types.id
group by 1
union
select car_types.name, 0
from car_types
left join cars on cars.car_type_id = car_types.id
where cars.car_type_id is null
union
select * from (select 'uncategorized', 0)
where exists (select * from cars where car_type_id is null)

仅供引用,coalesce() 从提供给它的值列表中返回第一个非空值,并且当以下情况时,左连接表中的所有列均为 null没有匹配的行。

关于Postgresql - 获取计数和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44273071/

相关文章:

postgresql - 从 Docker Compose 堆栈中的 ASP.NET Core 6 通过 Npgsql 连接到 PostgreSql

postgresql - 无法使用与文档匹配的语法创建触发器

java - 从 java 调用 pg_dump 时命令行参数过多

使用另一个表中的相同 ID 对列中的 SUM 值进行 SQL 查询

sql - 如何重写长查询?

MySQL 动态交叉表

ruby-on-rails - 运行 bundle 后安装 pg gem 时出错

mysql - 如何在使用 UNION 的查询中实现 SQL_CALC_FOUND_ROWS?

r - dplyr 计数变量的一个特定值的数量

mysql - 我如何计算 ON DUPLICATE KEY UPDATE MySQL -php 中更新行的总数