【问题标题】:do I need a new field for counting scores form another table?我需要一个新字段来计算另一个表的分数吗?
【发布时间】:2018-01-28 06:29:10
【问题描述】:

我有一个Users

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

我还有一个Votes 表。

用户可以对AB 进行投票。

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

我想向用户查询并统计AB 的投票。

假设我找到了一个 id 为 1 的用户,

我怎样才能得到类似的东西

{
        "id": 1,
        "display_name": "test",
        "A" : 32,
        "B" : 132
}

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

【问题讨论】:

    标签: postgresql function models objection.js


    【解决方案1】:

    简化表:

    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)
    

    【讨论】:

    • 谢谢,但我无法更改我的表,因为还有我在此示例中未提供的现有关系。
    • 我不是建议你...只是使用方法来对付你的桌子
    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多