我有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
我想让这些评分在用户头像上显示为饼图:
所以我正在尝试以下 -
首先从 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
将返回 true
。 false 或 null
将返回 null
。它全部转换为 float
以产生 float
返回。
至于为什么你的更新只产生空值我不知道。发布一些示例数据,以便我们可以使用它。
关于sql - 计算一个表中的商并将其存储在另一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17040692/