[英]MySQL query rows to columns
Does anyone know how to make rows into columns while still beign joined?有谁知道如何在仍然保持连接的情况下将行变成列?
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
The rows in column should be the columns and still be grouped by id with value列中的行应该是列,并且仍然按 id 和 value 分组
So it should look something like this:所以它应该看起来像这样:
Use conditional aggregation:使用条件聚合:
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
Note that I modified your query to use table aliases ( cf
, cfv
, p
): they make the query easier to write and read.请注意,我修改了您的查询以使用表别名(
cf
、 cfv
、 p
):它们使查询更易于编写和阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.