我需要将列转置为postgres中的行,下面是要求。 任何帮助表示赞赏。
来源表/数据:
id class-1-male class-1-female class-2-male class-2-female class-3-male class-3-female
1 1 1 11 7 0 9
2 11 31 6 7 40 92
3 15 31 8 37 30 91
4 11 13 50 17 10 19
我想要以下格式的数据:
id class-type male female
1 class-1 1 1
2 class-1 11 31
3 class-1 15 31
4 class-1 11 13
1 class-2 11 7
2 class-2 6 7
3 class-2 8 37
4 class-2 50 17
1 class-3 0 9
2 class-3 40 92
3 class-3 30 91
4 class-3 10 19
答案 0 :(得分:1)
如果你想做相反的事情(这更常见)你可以使用hte tablefunc
contrib模块。但是这样,您只需使用UNION ALL
并分别查询每个列:
SELECT id, 'class-1' AS class-type,
class-1-male AS male, class-1-female AS female
FROM your_table
UNION ALL
SELECT id, 'class-2' AS class-type,
class-2-male AS male, class-2-female AS female
FROM your_table
UNION ALL
SELECT id, 'class-3' AS class-type,
class-3-male AS male, class-3-female AS female
FROM your_table
如果此表上有太多行,这可能不是最佳选择,因为它会读取每个查询的整个数据集,这意味着它只读取一次就会读取它们三次。另一种选择是创建一个返回集合的函数:
CREATE OR REPLACE FUNCTION classes_transpose()
RETURNS TABLE(id int, class_type text, male int, female int)
LANGUAGE PLPGSQL
STABLE
AS $$
DECLARE
v RECORD;
BEGIN
FOR v IN SELECT * FROM your_table LOOP
id := v.id;
class_type := 'class-1';
male := v."class-1-male";
female := v."class-1-female";
RETURN NEXT;
class_type := 'class-2';
male := v."class-2-male";
female := v."class-2-female";
RETURN NEXT;
class_type := 'class-3';
male := v."class-3-male";
female := v."class-3-female";
RETURN NEXT;
END LOOP;
END;
$$;
然后:
SELECT * FROM classes_transpose();