简体   繁体   English

PostgreSQL-CrossTab或带有可变数字列的数据透视表

[英]Postgresql - CrossTab or Pivot with Variable number column

I need to make a query using pivot or crosstab with columns variables. 我需要使用带有列变量的数据透视表或交叉表进行查询。 Is possible? 有可能吗 I have the following table: 我有下表:

Data_Id ! Description_Column | Value
--------+--------------------+-------
1       ! Column1            ! value1
1       ! Column2            ! value2 
1       ! Column3            ! value3
1       ! Column4            ! value4
2       ! Column1            ! value5
2       ! Column2            ! value6
2       ! Column3            ! value7
2       ! Column4            ! value8

I will need get 我需要得到

Data_Id ! Column1 ! Column2 ! Column3 ! Column4
1       ! value1  ! value2  ! value3  ! value4
2       ! value5  ! value6  ! value7  ! value8

But sometimes i will have: 但是有时候我会:

Data_Id ! Description_Column | Value
--------+--------------------+-------
3       ! Column1            ! value1
3       ! Column2            ! value2 
4       ! Column1            ! value5
4       ! Column2            ! value6

I will need get 我需要得到

Data_Id ! Column1 ! Column2 
3       ! value1  ! value2  
4       ! value5  ! value6  

Obs. 观察 The rows that I'll need will be selected through a Join. 我需要的行将通过联接选择。 So I will have the number of variable columns. 因此,我将获得可变列的数量。

Thanks for help. 感谢帮助。

You have to remember that the SQL planner needs to know at plan time what a return row looks like in rough terms. 您必须记住,SQL计划者需要在计划时知道返回行的大致含义。 So you can't do this directly. 因此,您不能直接执行此操作。

The first is you can create a function which does what you are trying to do and returns the result in a refcursor. 首先是您可以创建一个函数,该函数执行您要尝试执行的操作并将结果返回给refcursor。 That's probably the easiest way to do it. 那可能是最简单的方法。 Use the crosstab() function from the tablefunc contrib module/extension. 使用tablefunc contrib模块/扩展中的crosstab()函数。 You should be able to generate the SQL query to run based on querying the data but that requires in-function dynamic SQL and again you'd have to return a refcursor. 您应该能够基于查询数据来生成要运行的SQL查询,但这需要功能内动态SQL,并且再次需要返回一个refcursor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM