postgresql 储存过程的问题

lenovoAdmin888 2011-02-28 12:03:33
有三个张organ, fillquestiontype, organontype表
organ表
organcode organname
1012 腾讯
2013 盛大
fillquestiontype表
id name
1 安全
2 环保
3 社会
4 历史
5 质量
organontype表关联上两张表
id oid tid score
1 1012 1 53
2 1012 2 54
3 2013 1 56
4 2013 2 57
....

想要这样的结果
oid 安全 环保
腾讯 53 54
盛大 56 57

以下是postgresql 储存过程的写法,大家看看有什么错?

CREATE OR REPLACE FUNCTION organontype(bpchar) RETURNS integer AS
$BODY$DECLARE
strWhere character(20000);
BEGIN
strWhere := 'select oid'
select strWhere = strWhere ||',max(case tid when''' || tid || ''' then score else 0 end)[' || tid || ']'
from (select distinct tid from (select o.organname as oid,t.name as tid,ot.score from organontype as ot,organ as o,fillquestiontype as t where o.organcode=ot.oid and t.id=ot.tid) as d) as a
strWhere := strWhere || ' from (select o.organname as oid,t.name as tid,ot.score from organ as o,fillquestiontype as t,organontype as ot where o.organcode=ot.oid and t.id=ot.tid) as c group by oid'
strWhere := 'select oid,'|| $1 || ' from (' || strWhere ||') as abc '
return 0;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;

参数传的是fillquestiontype的name字段
比如传 '安全'
显示
oid 安全
传 '安全,环保'
显示
oid 安全 环保




...全文
57 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
WWWWA 2011-03-01
  • 打赏
  • 举报
回复
for r in select distinct "B" from tth1 loop
ff:=ff || 'max(case when "B"='''||r."B" || '''' || ' then "C" ' || ' end ),';
RAISE NOTICE '123(%)', ff;
end loop;

1楼的代码都有,仔细看看
lenovoAdmin888 2011-03-01
  • 打赏
  • 举报
回复
如何循环累加啊 能否给个示例
mysqldbd 2011-02-28
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wwwwa 的回复:]
引用 2 楼 lenovoadmin888 的回复:
楼上的看不懂啊

说简单点,就是postgresql里如何实现动态行转列

看看PG的HELP吧,1楼的代码就是动态行转列的,与其它的数据库不同,要用循环累加字符串,而不是直接在SQL语句中累加
[/Quote]

支持,就是这样的,PG跟别的不太一样的。
WWWWA 2011-02-28
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 lenovoadmin888 的回复:]
楼上的看不懂啊

说简单点,就是postgresql里如何实现动态行转列
[/Quote]
看看PG的HELP吧,1楼的代码就是动态行转列的,与其它的数据库不同,要用循环累加字符串,而不是直接在SQL语句中累加
lenovoAdmin888 2011-02-28
  • 打赏
  • 举报
回复
楼上的看不懂啊

说简单点,就是postgresql里如何实现动态行转列
wwwwb 2011-02-28
  • 打赏
  • 举报
回复
给你1个示例,自行修改
CREATE FUNCTION dt1() RETURNS SETOF record AS $$
declare r record;
ff varchar:='SELECT "A",';
begin
for r in select distinct "B" from tth1 loop
ff:=ff || 'max(case when "B"='''||r."B" || '''' || ' then "C" ' || ' end ),';
RAISE NOTICE '123(%)', ff;
end loop;
ff:=substr(ff,1,length(ff)-1) || ' from tth1 group by "A"';
FOR r IN execute ff Loop
RETURN NEXT r;
END LOOP;
end;
$$ LANGUAGE plpgsql;

select * from dt1() a(q text,d float,e float,f float);

954

社区成员

发帖
与我相关
我的任务
社区描述
PostgreSQL相关内容讨论
sql数据库数据库架构 技术论坛(原bbs)
社区管理员
  • PostgreSQL社区
  • yang_z_1
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧