測試對象:
create table t (sun numeric,
mon numeric,
tue numeric,
wed numeric,
thu numeric,
fri numeric);
insert into t(sun, mon, tue, wed, thu, fri)
values(1.24, 1.11, 4.51, 3.21, 2.21, 1.01);
alternat香港專業教育學院改爲@非理性的回答沒有union
:
select day[i], amount[i]
from (select generate_series(1,6) as i,
array['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'] as day,
array[sun, mon, tue, wed, thu, fri] as amount
from t) z;
,如果你需要更通用的,你可以做這樣的事情:
create or replace function unpivot(t) returns setof record
language plpgsql immutable strict as $$
declare
q record;
r record;
begin
for q in (select attname, attnum
from pg_attribute
where attnum>0 and attrelid = (select oid
from pg_class
where relname = 't')) loop
for r in execute 'select '''||q.attname||'''::text, '||
'('||$1::text||'::t).'||q.attname||'::numeric' loop
return next r;
end loop;
end loop;
return;
end;$$;
select *
from unpivot((select row(t.*)::t from t))
as foo(day text, amount numeric);
,你可能會有點整潔的8.4與一個using
條款在execute
但我不能測試,因爲我在8.3
相關的問題是http://stackoverflow.com/questions/1128737/unpivot-and-postgresql – Unreason 2010-12-01 21:03:50