Question

I have a PHP script displaying a list of players sorted by their "virtual money":

$sth = $db->prepare("
select u.id,
        u.first_name,
        u.city,
        u.avatar,
        m.money,
        u.login > u.logout as online
from pref_users u, pref_money m where
        m.yw=to_char(current_timestamp, 'IYYY-IW') and
        u.id=m.id
order by m.money desc
limit 20 offset ?
");
$sth->execute(array($_GET['offset']));

To show a player position in the list I use a PHP variable $pos which is incremented in a loop while printing their names and further data.

I would like to have that position in the SQL statement instead of PHP for various reasons. So I'm trying the following:

$sth = $db->prepare("
select u.id,
        row_number() + ? as pos,
        u.first_name,
        u.city,
        u.avatar,
        m.money,
        u.login > u.logout as online
from pref_users u, pref_money m where
        m.yw=to_char(current_timestamp, 'IYYY-IW') and
        u.id=m.id
order by m.money desc
limit 20 offset ?
");
$sth->execute(array($_GET['offset'], $_GET['offset']));

But get the ERROR: window function call requires an OVER clause

I'm trying to add over(m.money) but get a syntax error.

I'm probably misunderstanding the Window Functions doc.

Was it helpful?

Solution

Check the user notes on: http://www.postgresql.org/docs/8.4/interactive/functions-window.html

You will need the Over() to contain the same order by clause as the whole query:

$sth = $db->prepare("
select u.id,
        row_number() OVER (order by m.money desc) + ? as pos,
        u.first_name,
        u.city,
        u.avatar,
        m.money,
        u.login > u.logout as online
from pref_users u, pref_money m where
        m.yw=to_char(current_timestamp, 'IYYY-IW') and
        u.id=m.id
order by m.money desc
limit 20 offset ?
");
$sth->execute(array($_GET['offset'], $_GET['offset']));

OTHER TIPS

You want row_number() OVER (ORDER BY m.money) + ? etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top