我如何在一个函数中放一个表?

时间:2017-11-20 11:28:30

标签: postgresql

id_session,x,z,time
1,-10,-10,0
1,-10,-10,1
1,-5,-4,2

我有这个功能:

Select x.x,x.z,sum(case when x=nextlat and z=nextlng then 0 else 1 end ) s
From
(    Select x,
            z,
            lead(x,1,-9999) over (order by tempo) nextlat,              
             lead(z,1,-9999) over (order by tempo) nextlng
            from xmltrack where id_session = 1
) x
Group by x.x,x.z
order by s desc

如何使用id_session作为参数创建函数? 像这样:

CREATE OR REPLACE FUNCTION xmlintersezioni (idsession integer)
  RETURNS TABLE (cx integer, cz integer, cs integer) AS $$
     BEGIN
    RETURN QUERY Select x.x,x.z,sum(case when x=nextlat and z=nextlng then 0 else 1 end ) s
            From 
           (select x,
            z,
            lead(x,1,-9999) over (order by tempo) nextlat,              
             lead(z,1,-9999) over (order by tempo) nextlng
            from xmltrack where id_session = idsession
) x
Group by x.x,x.z
order by s desc;     
END; $$
LANGUAGE 'plpgsql';

1 个答案:

答案 0 :(得分:0)

我假设id_session是一种自定义类型 - 如下所示:

create type id_session_type AS <whatever>;

create table xmltrack (
  id_session id_session_type,
  x integer,
  y integer,
  z integer
);

在这种情况下,我认为您需要做的就是在函数中使用相同的数据类型:

CREATE OR REPLACE FUNCTION xmlintersezioni (idsesssion id_session_type)