所以我有兩個表,播放機和結構,像這樣匹配:彙總總計給出多個條件
Table "public.players"
Column | Type | Modifiers
--------+---------+------------------------------------------------------
id | integer | not null default nextval('players_id_seq'::regclass)
name | text |
wins | integer | default 0
loses | integer | default 0
rating | integer | default 1500
和
Table "public.matches"
Column | Type | Modifiers
---------------+---------+------------------------------------------------------
id | integer | not null default nextval('matches_id_seq'::regclass)
player1 | integer |
player1rating | integer |
player2 | integer |
player2rating | integer |
winner | boolean |
在哪裏,如果PLAYER1贏得了那場比賽,或者如果player2假的贏家是真實的贏得了比賽。
使用球員表進行簡單的贏/輸比較很簡單,但我正在觀察比較兩名球員相互面對對手的情況,以及他們對對方的記錄。
所以我對我怎麼會總結困惑,其中給出一個給定的球員可能被列爲要麼PLAYER1或player2條件: P1勝率:
(player1 = <player1> AND winner = true) OR (player2 = <player1> AND winner = false)
P2勝率:
(player1 = <player2> AND winner = true) OR (player2 = <player2> AND winner = false)
損失只會與其他玩家獲勝相反。
東西返回的信息,如:
id | name | wins | loses | rating | wins_v_opp | loses_v_opp
------+----------+------+-------+--------+------------+------------
4200 | Sinku | 5 | 48 | 1191 | 1 | 4
4201 | Kenshiro | 33 | 29 | 1620 | 4 | 1
我想出什麼樣的主意UPDATE2低於前:
CREATE FUNCTION matchup(text, text) AS $$
DECLARE
player1_name ALIAS FOR $1;
player2_name ALIAS FOR $2;
BEGIN
EXECUTE 'SELECT id FROM player WHERE name LIKE $1'
INTO player1_id
USING player1_name;
IF NOT FOUND THEN
RAISE EXCEPTION 'Player1 % not found', player1_name;
END IF;
EXECUTE 'SELECT id FROM player WHERE name LIKE $1'
INTO player2_id
USING player2_name;
IF NOT FOUND THEN
RAISE EXCEPTION 'Player2 % not found', player2_name;
END IF;
RETURN QUERY EXECUTE 'WITH cte_winners AS (
SELECT
CASE WHEN winner THEN m.player1 ELSE m.player2 END AS player,
COUNT(*) AS wins_v_opp,
sum(count(*)) over() - COUNT(*) AS loses_v_opp
FROM matches AS m
WHERE player1 IN ($1,$2) AND player2 IN ($1,$2)
GROUP BY player
)
SELECT * FROM players AS p
LEFT OUTER JOIN cte_winners AS cw ON cw.player = p.id WHERE p.id IN ($1,$2)'
USING player1_id,player2_id;
END;
$$ LANGUAGE plpgsql;
我就更新了原來的職位:) – OverlordQ
@OverlordQ您的評論還沒有完成:) –
現在$ 10,000的問題是,如果我不知道前面的玩家ID我想按名稱選擇,我不需要加入CTE的球員嗎? – OverlordQ