首页 > 解决方案 > postgressql/typeorm - 在同一张表上使用过滤器计数并与另一个表连接

问题描述

我正在使用 PostgresSQL 作为 DBMS 和 typeorm 作为 ORM 我需要编写一个对我来说有点复杂的查询。看起来像这样的数据库结构:

Results
| PersonId | Result   |
|----------|----------|
| 1        | Rejected |
| 1        | Rejected |
| 1        | Passed   |
| 1        | Passed   |
| 2        | Rejected |
| 2        | Passed   |
| 3        | Rejected |
| 3        | Rejected |
| 3        | Rejected |
| 3        | Rejected |
| 3        | Passed   |

OtherTable
| PersonId | OtherColumn |
|----------|-------------|
| 1        | ...         |
| 1        | ...         |
| 1        | ...         |
| 2        | ...         |
| 2        | ...         |
| 3        | ...         |
| 3        | ...         |
| 3        | ...         |
| 3        | ...         |

我如何为每个人获得他们被拒绝和通过的次数?在同一个查询中它们出现在另一个查询中的次数是否可能?

| PersonId | Rejected | Passed | CountFromOtherTable
|----------|----------|--------| -----------------
| 1        | 2        | 2      | 3
| 2        | 1        | 1      | 2
| 3        | 4        | 1      | 3

只是 SQL 查询也很好,我可以尝试将其翻译为与 typeorm 一起使用。

标签: sqlpostgresqljoincounttypeorm

解决方案


基本上,您需要条件聚合。在 Postgres 中,我建议使用filterand left join

select r.PersonId,
       count(*) filter (where r.result = 'Rejected') as Rejected,
       count(*) filter (where r.result = 'Passed') as Passed
       coalesce(o.cnt, 0) as other_table_cnt
from Results r left join
     (select personid, count(*) as cnt
      from othertable o
      group by personid
     ) o
     using (personid)
group by r.PersonId;

注意:这假设您想要第一个表中的所有人,因此left join. 如果您想要两个表中的所有人,请使用inner join. 如果您想要任一表中的所有人,请使用full join.


推荐阅读