postgresql - 将总计分组匹配到总计的好方法是什么

标签 postgresql

我有以下问题。看似很简单的一个查询,但我花了那么多时间也没弄明白。

Table
-----
project
mission
craft

project can have many missions, for each mission, it can use multiple air crafts. I want to identify the crafts that was involved with all the missions.

For eg if there are 10 missions, mission 1 can use craft 1 and 2. If there is any craft that used for all the 10 missions (mission 1 -10), that should be output.

I wrote,

select craft,count(mission) from table group by craft

在此之后我不知道如何将这个值与任务总数相匹配。任何帮助将不胜感激。

最佳答案

如果你需要这个用于单个项目,你需要按任务总数过滤工艺任务数:

select c.id from (
   select c.id, count(mission_id) cnt
   from craft c inner join mission m on (m.id = c.mission_id)
   where m.project_id = <project_id> 
   group by c.id
) as c 
where c.cnt = (select count(*) from mission where project_id = <project_id>)

如果所有项目都需要这个:

select c.project_id, c.id from (
   select m.project_id, c.id, count(mission_id) cnt
   from craft c inner join mission m on (m.id = c.mission_id) 
   group by m.project_id, c.id
) as c inner join (
   select project_id, count(*) cnt
   from mission
   group by project_id
) as m on (m.project_id = c.project_id)
where c.cnt = m.cnt

关于postgresql - 将总计分组匹配到总计的好方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22591913/

相关文章:

sql - 加入倾斜关系时,有没有办法改进 PostgreSQL 估计?

postgresql - 如果我删除了一个带索引的 PG 表,这个索引还存在吗?

django - 随机数据库与 AWS 中的 Django 和 Postgresql 断开连接

python - 外部文件中的 SQLAlchemy 枚举

sql - 是否有一个命令结合了 SQL 中 UNION 和 JOIN 的功能?

sql - PostgreSQL - select 语句中的 if 子句

sql - 使用一个查询中的 id 值到另一表中具有相同 id 的对应列

sql - 错误消息 : "PostgreSQL said: could not write block 119518 of temporary file: No space left on device" PostgreSQL

postgresql - 数据库中的版本控制

通过 Docker 的 Postgresql - postgres 没有自动运行