我想在表格下方旋转/交叉表
我在PostgreSQL中尝试了以下查询,但给出错误ERROR:无效的返回类型 详细信息:查询指定的返回元组有6列,但交叉表返回5
SELECT * FROM crosstab(
'select Key,status,v_text,v_number,v_dob from table
where type = ''First_Name'' or type = ''Last_Name'' or type = ''DOB'' or type = ''Contact'' order by 1',
'select distinct type from table where type = ''First_Name'' or type = ''Last_Name'' or type = ''DOB'' or type = ''Contact'' order by 1')
AS ct( Key int, First_Name text, Last_Name text, DOB date, Contact int);
所需的输出如下所示,其中所有类型都有值。在pgsql中可以吗
答案 0 :(得分:1)
我建议条件聚合。这是标准的SQL语法,并且比诸如crosstab
之类的特定于供应商的实现要灵活得多:
select
key,
status,
max(v_text) filter(where type = 'FistName') first_name,
max(v_text) filter(where type = 'LastName') last_name,
max(v_date) filter(where type = 'DOB') dob,
max(v_number) filter(where type = 'Contact') contact
from mytable
group by key, status
答案 1 :(得分:1)
您可以按照以下步骤进行操作-
select key,
status,
max(case when type = 'First name' then v_text end) As first_name,
max(case when type = 'Last name' then v_text end) As last_name,
max(case when type = 'DOB' then v_date end) As DOB,
max(case when type = 'Contact' then v_number end) As Contact
from mytable
group by key, status;