我有一个postgres数据库,其数据结构设置如下。
我有一张评估表和一张处方表。评估可以有许多与之相关的处方。处方只能有一个与之相关的评估。
我遇到的问题是我希望能够导出此数据的CSV。期待,我希望格式全部在CSV中的一行。如果评估有1个处方,则在csv中应该有recipe_name_1等的列。如果评估有5个处方,我希望它扩展到prescription_name_1,prescription_name_2,prescription_name_3,prescription_name_4,prescription_name_5。有效地对这些数据进行非规范化。
不确定数据库是否可以这样做,或者我是否必须坚持使用此类逻辑的应用程序层。
答案 0 :(得分:0)
查询,得到非规范化数据:
SELECT evaluation.name || '_' || CASE WHEN prescription.counts IS NULL
THEN 0
ELSE prescription.counts END
AS denormalized_name
FROM evaluations evaluation LEFT OUTER JOIN (
SELECT
count(id) counts,
evaluation_id
FROM prescription
GROUP BY evaluation_id
) prescription
ON evaluation.id = prescription.evaluation_id
然后,您可以通过以下方式将其复制到csv:
Copy (%query%) To '/var/test.csv' With CSV;
答案 1 :(得分:0)
这有点像黑客,但这样的事情可能有用。假设你的处方 - >评估关系位于名为prescription
的对象中:
create table prescription (
prescription_name text,
evaluation_name text
);
然后您可以使用数组,将其强制转换为文本,然后去掉渲染数组的可视元素 - 开始和结束花括号:
with array_query as (
select
p1.evaluation_name, array (
select p2.prescription_name
from prescription p2
where p1.evaluation_name = p2.evaluation_name
)::text as prescriptions
from
prescription p1
group by
p1.evaluation_name
)
select
evaluation_name || ',' ||
replace (replace (prescriptions, '{', ''), '}', '')
from array_query
输入:
insert into prescription values ('Prescription 1', 'Eval 1');
insert into prescription values ('Prescription 2', 'Eval 1');
insert into prescription values ('Prescription 3', 'Eval 1');
insert into prescription values ('Prescription 4', 'Eval 2');
insert into prescription values ('Prescription 5', 'Eval 2');
insert into prescription values ('Prescription 6', 'Eval 2');
insert into prescription values ('Prescription 7', 'Eval 2');
输出:
Eval 2,"Prescription 4","Prescription 5","Prescription 6","Prescription 7"
Eval 1,"Prescription 1","Prescription 2","Prescription 3"