 ) AS $func$
 SELECT id, name, SUM(matchesByPlayers.score) AS points,
 		COUNT(matchesByPlayers.match) AS matches
-        FROM matchesByPlayersInEvent(actualEvent) as matchesByPlayers
+        FROM matchesByPlayersInEvent(currentEvent) as matchesByPlayers
         GROUP BY id, name 
         ORDER BY points DESC, name ASC;
 $func$  LANGUAGE sql;

	id SERIAL PRIMARY KEY
);

CREATE OR REPLACE FUNCTION activePlayersInEvent(actualEvent INTEGER)
RETURNS TABLE(
	id INTEGER,
	name TEXT
) AS $func$
SELECT players.id, (firstname || ' ' || lastname) as name 
        FROM players, playersInEvent WHERE event=actualEvent 
        AND players.id=playersInEvent.player;
$func$  LANGUAGE sql;


CREATE OR REPLACE FUNCTION matchesByPlayersInEvent(actualEvent INTEGER)
RETURNS TABLE(
	id INTEGER,
	name TEXT,

        ELSE 0.0
    END as score
	, matches.id as match 
	FROM (SELECT * FROM activePlayersInEvent(currentEvent)) as activePlayers
	LEFT JOIN matches ON (activePlayers.id = matches.player_one) or 
        (activePlayers.id = matches.player_two)
$func$  LANGUAGE sql;


-- Store procedure: Standings
-- It has aggregation functions to determine:
-- number of matches and total points earned in that matches
CREATE OR REPLACE FUNCTION standings(currentEvent INTEGER)
RETURNS TABLE(
	id INTEGER,
	name TEXT,
