我是否需要一个新的字段来计算另一个表的分数?

时间:2018-01-28 06:29:11

标签: postgresql function models objection.js

我有Users

它有id,用户名,AB作为我的列。

我还有Votes表。

用户可以对AB进行投票。

它有id,user_id外键,A_id外键和B_id外键。

我想对用户进行查询,并获得A的投票数和B投票数。

所以我想找一个id为1的用户

我如何得到像

这样的东西
{
        "id": 1,
        "display_name": "test",
        "A" : 32,
        "B" : 132
}

假设Votes表中有32行,而Votes表中有B行为132行。

1 个答案:

答案 0 :(得分:0)

简化表:

t=# select* from users;
 i | t
---+---
 1 | A
 1 | B
 1 | B
 2 | A
 2 | A
 2 | B
(6 rows)

查询:

t=# select distinct
i
, sum(case when t='A' then count(1) filter (where t='A') else 0 end) over (partition by i) a
, sum(case when t='B' then count(1) filter (where t='B') else 0 end ) over (partition by i)b
from users
group by i,t
order by i;
 i | a | b
---+---+---
 1 | 1 | 2
 2 | 2 | 1
(2 rows)
相关问题