sql - 计算一个表中的商并将其存储在另一个表中

标签 sql postgresql postgresql-8.4

我有a small Facebook card game用户可以在这里互相评价。

这些评分作为 bool 值 nice 存储在 PostgreSQL 8.4.13 表 pref_rep 中,也可以为 null:

# \d pref_rep;
                                       Table "public.pref_rep"
  Column   |            Type             |                         Modifiers
-----------+-----------------------------+-----------------------------------------------------------
 id        | character varying(32)       | not null
 author    | character varying(32)       | not null
 nice      | boolean                     |
 comment   | character varying(256)      |
 rep_id    | integer                     | not null default nextval('pref_rep_rep_id_seq'::regclass)
Indexes:
    "pref_rep_pkey" PRIMARY KEY, btree (id, author)
Check constraints:
    "pref_rep_check" CHECK (id::text <> author::text)
Foreign-key constraints:
    "pref_rep_author_fkey" FOREIGN KEY (author) REFERENCES pref_users(id) ON DELETE CASCADE
    "pref_rep_id_fkey" FOREIGN KEY (id) REFERENCES pref_users(id) ON DELETE CASCADE

我想让这些评分在用户头像上显示为饼图:

enter image description here

所以我正在尝试以下 -

首先从 pref_rep 中选择一个商(nice/nice + not nice):

# select id,
    (count(nullif(nice, false)) - count(nullif(nice, true))) / count(nice) as rating
    from pref_rep
    where nice is not null
    group by id;

           id            | rating
-------------------------+--------
 DE10072                 |     -1
 DE10086                 |      0
 DE10087                 |      1
 DE10088                 |     -1
 DE10095                 |      0
 DE10097                 |      1
 DE10105                 |      0

为什么这里不打印 0 到 1 的 float ?

然后我试图将该商存储在 pref_users 表中 - 由于性能原因,我想通过每晚的 cronjob 来完成:

# update pref_users u
set rating = s.rating
from (
        select
        id,
        count(nullif(nice, false)) - count(nullif(nice, true)) / count(nice) as rating
        from pref_rep
        where nice is not null
        group by id
) s
where u.id = s.id;

UPDATE 25419

这很快完成,但是为什么 pref_users 中的所有 rating 值都设置为 null?

最佳答案

评分:

select id,
    coalesce(
        (count(nice or null) - count(not nice or null))::float
        / count(nice)
    , 0) as rating
from pref_rep
group by id;

count 不计算空值。 true 或 null 将返回 truefalse 或 null 将返回 null。它全部转换为 float 以产生 float 返回。

至于为什么你的更新只产生空值我不知道。发布一些示例数据,以便我们可以使用它。

关于sql - 计算一个表中的商并将其存储在另一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17040692/

相关文章:

mysql - SQL:按Column2降序选行,Column1不为NULL时只显示1条结果

sql - ORA-00936 : missing expression vb. 净 - 甲骨文

sql - 如何获得SQLite中X列与Y列的比率?

postgresql - PostgreSQL中如何设置sub select的表空间

sql - 在 Liquibase 中执行第二次插入时如何引用自动递增的 ID?

python - psycopg2.OperationalError : FATAL: unsupported frontend protocol 1234. 5679 : server supports 2. 0 到 3.0

sql - 尝试查找不同的数据时返回相同的结果

c# - 基于 PIVOT 查询的 Oracle View 不是空值

sql - 将逗号分隔的列数据拆分为其他列

postgresql - Postgres - 降低值后查找重复值