4

我有一张桌子,上面有每周玩家的分数:

# select * from pref_money limit 5;
       id       | money |   yw
----------------+-------+---------
 OK32378280203  |   -27 | 2010-44
 OK274037315447 |   -56 | 2010-44
 OK19644992852  |     8 | 2010-44
 OK21807961329  |   114 | 2010-44
 FB1845091917   |   774 | 2010-44
(5 rows)

这条 SQL 语句为我提供了每周的获胜者以及每个玩家获胜的次数:

# select x.id, count(x.id) from (
    select id,
           row_number() over(partition by yw order by money desc) as ranking
    from pref_money
) x
where x.ranking = 1 group by x.id;
           id           | count
------------------------+-------
 OK9521784953           |     1
 OK356310219480         |     1
 MR797911753357391363   |     1
 OK135366127143         |     1
 OK314685454941         |     1
 OK308121034308         |     1
 OK4087658302           |     5
 OK452217781481         |     6
....

我想将后一个数字保存在medals玩家表的列中:

# \d pref_users;
                   Table "public.pref_users"
   Column   |            Type             |     Modifiers
------------+-----------------------------+--------------------
 id         | character varying(32)       | not null
 first_name | character varying(64)       |
 last_name  | character varying(64)       |
 city       | character varying(64)       |
 medals     | integer                     | not null default 0

请问这个怎么做?我只能想到使用临时表,但必须有更简单的方法...谢谢

更新:

Clodoaldo 建议的查询有效,但现在我的 cronjob 偶尔会失败:

/* reset and then update medals count */
update pref_users set medals = 0;
psql:/home/afarber/bin/clean-database.sql:63: ERROR:  deadlock detected
DETAIL:  Process 31072 waits for ShareLock on transaction 124735679; blocked by process 30368.
Process 30368 waits for ShareLock on transaction 124735675; blocked by process 31072.
HINT:  See server log for query details.

update pref_users u
set medals = s.medals
from (
    select id, count(id) medals
    from (
        select id,
            row_number() over(partition by yw order by money desc) as ranking
        from pref_money where yw <> to_char(CURRENT_TIMESTAMP, 'IYYY-IW')
    ) x
    where ranking = 1
    group by id
) s
where u.id = s.id;
4

2 回答 2

1

您可以创建一个使用“奖牌选择”并将其与实际数据连接起来的视图:

CREATE VIEW pref_money_medals AS
SELECT *
FROM pref_money
JOIN (SELECT count(x.id)
      FROM (SELECT id, row_number() 
            OVER(PARTITION BY yw ORDER BY money DESC) AS ranking
            FROM pref_money
            ) x
      WHERE x.ranking = 1 group by x.id) medals
ON pref_money.id = medals.id;
于 2013-01-29T10:26:46.467 回答
1
update pref_users u
set medals = s.medals
from (
    select id, count(id) medals
    from (
        select id,
            row_number() over(partition by yw order by money desc) as ranking
        from pref_money
    ) x
    where ranking = 1
    group by id
) s
where u.id = s.id
于 2013-01-29T10:45:21.793 回答