sql - 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 一起使用。
解决方案
基本上,您需要条件聚合。在 Postgres 中,我建议使用filter
and 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
.
推荐阅读
- ssas - 基于strtomember访问前一个成员
- javascript - 在 express 中将绝对 url 路径传递给车把视图
- swift - 结合 Semaphore 来限制 .notify 的异步请求和调度组与 defer 和 App 冻结
- android - 亚行以退出代码 1 退出
- java - 如何在 Java 中使用 BufferedReader 在 .txt 文件中查找特定字符串
- java - 错误:由 OutputStream.flush() 引起的“nativeDrain 中没有错误”
- c# - 在一个时间点监听两个事件的方法的执行时间c#
- vue.js - 如何在 jsx 中使用 vue-matrial 表?
- java - 如何从android java String中提取子字符串?
- c++ - 成对展开可变参数模板包