问题描述
有人知道如何在仍保持良好联接的情况下将行划分为列吗?
SELECT p.id,f.title 'column',v.value
FROM custom_fields f
JOIN custom_field_values v
ON v.custom_field_id = f.id
JOIN projects p
ON p.id = v.related_to_id
WHERE p.deleted = 0
列中的行应为列,并且仍按ID和值分组
所以它应该看起来像这样:
解决方法
使用条件聚合:
select
p.id,max(case when cf.title = 'Rental (FSG)' then cfv.value end) rental_fsg,max(case when cf.title = 'Model Year' then cfv.value end) model_year,max(case when cf.title = 'Product' then cfv.value end) product,max(case when cf.title = 'Partner' then cfv.value end) partner,max(case when cf.title = 'SAP delivery / invoice number' then cfv.value end) sap_delivery
from custom_fields cf
join custom_field_values cfv on cfv.custom_field_id = cf.id
join projects p on p.id = cfv.related_to_id
where p.deleted = 0
group by p.id
请注意,我将查询修改为使用表别名(cf
,cfv
,p
):它们使查询更易于编写和读取。