我正在尝试执行一个查询,其中我传递了'seasson',它向我显示了与排名中的驱动程序,积分,构造函数和位置相关的信息。
我想要的是这样的东西:
POS IN RANKING | DRIVER NAME | CONSTRUCTOR NAME | POINTS
---------------------------------------------------------
1 "Hamilton" MC Laren 360
2 "Alonso" Ferrari 290
... ... ....
我得到的问题是我无法枚举行。我认为“POS IN RANKING”应该是函数row_number()的结果,但是对于某些reasson我不能使它工作。
这是我的存储功能:
CREATE TYPE ranking_t AS (
pos integer,
driver character varying(30),
constructor character varying(30),
points integer
);
CREATE OR REPLACE FUNCTION pra2.GetRankingOfPilots(sea pra2.season.name%type)
RETURNS ranking_t AS $$
DECLARE
ranking_pilots ranking_t;
BEGIN
SELECT
row_number() OVER (ORDER BY totalpuntos),
driver.name driver,
constructor.name constructor,
season.name season,
CAST(sum(runs.points) AS int) TotalPuntos
INTO ranking_pilots
FROM
pra2.hired hired
INNER JOIN pra2.constructor on hired.name_constructor = pra2.constructor.name
INNER JOIN pra2.driver on hired.num_driver = pra2.driver.num
INNER JOIN pra2.runs on pra2.driver.num=pra2.runs.num_driver
INNER JOIN pra2.race on pra2.runs.name_race=pra2.race.name AND pra2.runs.season_fk=pra2.race.season_fk AND pra2.runs.season_fk=pra2.race.season_fk
INNER JOIN pra2.season on hired.name_season=pra2.season.name AND pra2.race.season_fk=pra2.season.name
WHERE
pra2.season.name=sea
GROUP BY
season,driver,constructor
ORDER BY
TotalPuntos Desc;
END;
$$
LANGUAGE plpgsql;
我很感激任何建议。
提前谢谢!
答案 0 :(得分:1)
在包装器查询中获取行号。
另外:将返回类型更改为SETOF ranking_t
,删除变量并使用RETURN QUERY
。
CREATE OR REPLACE FUNCTION pra2.GetRankingOfPilots(sea pra2.season.name%type)
RETURNS SETOF ranking_t AS $$
BEGIN
RETURN QUERY
SELECT row_number() OVER (ORDER BY totalpuntos)::int, *
FROM (
SELECT
driver.name driver,
constructor.name constructor,
season.name season,
CAST(sum(runs.points) AS int) TotalPuntos
FROM
pra2.hired hired
INNER JOIN pra2.constructor on hired.name_constructor = pra2.constructor.name
INNER JOIN pra2.driver on hired.num_driver = pra2.driver.num
INNER JOIN pra2.runs on pra2.driver.num=pra2.runs.num_driver
INNER JOIN pra2.race on pra2.runs.name_race=pra2.race.name AND pra2.runs.season_fk=pra2.race.season_fk AND pra2.runs.season_fk=pra2.race.season_fk
INNER JOIN pra2.season on hired.name_season=pra2.season.name AND pra2.race.season_fk=pra2.season.name
WHERE
pra2.season.name=sea
GROUP BY
season,driver,constructor
) s
ORDER BY
TotalPuntos Desc;
END;
$$
LANGUAGE plpgsql;
答案 1 :(得分:0)
我想问题是你使用别名而不是源。
你不能这样做
SELECT row_number() OVER (ORDER BY totalpuntos)
FROM ( SELECT CAST(sum(runs.points) AS int) TotalPuntos
From YourQuery
) as Subquery
所以你创建一个子查询
OVER
也许你可以使用这个功能,但是SELECT
row_number() OVER (ORDER BY CAST(sum(runs.points) AS int)),
内部不确定是否可能。
CREATE OR REPLACE FUNCTION foo(a int)
RETURNS TABLE(b int, c int) AS $$
BEGIN
RETURN QUERY SELECT i, i+1 FROM generate_series(1, a) g(i);
END;
$$ LANGUAGE plpgsql;
编辑:要返回您喜欢的表
{{1}}