将存储为行的名称-值对转换为列

bkhjykvo  于 2021-06-21  发布在  Mysql
关注(0)|答案(5)|浏览(314)

我有一张table如下:

ID  | FieldName     | FieldValue
--------------------------------
01  | event_name    | Event Title
01  | event_cost    | 10.00
01  | event_loc     | Leeds
02  | event_name    | Another Event
02  | event_cost    | 15.00
02  | event_loc     | London

我想查询并返回如下结果:

Title           | Cost  | Location
------------------------------------
Event Title     | 10.00 | Leeds
Another Event   | 15.00 | London

最好的办法是什么?我尝试过使用select查询,但只能返回一个字段值,而且似乎无法加入它们。

jutyujz0

jutyujz01#

使用条件聚合。 GROUP_CONCAT 如果特定字段名有多个匹配项,则可以使用返回逗号分隔的列表。

SELECT
    ID,
    GROUP_CONCAT(CASE WHEN FieldName = 'event_name' THEN FieldValue END) AS Title,
    GROUP_CONCAT(CASE WHEN FieldName = 'event_cost' THEN FieldValue END) AS Cost,
    GROUP_CONCAT(CASE WHEN FieldName = 'event_loc'  THEN FieldValue END) AS Location
FROM yourdata
GROUP BY ID
xfyts7mz

xfyts7mz2#

尝试此查询:

SELECT event_name AS 'Title', event_cost AS 'Cost', event_loc AS 'Location' 
FROM yourTableName
cclgggtu

cclgggtu3#

使用案例

select id, max( case when FieldName='event_name' then FieldValue end) as Title,
max(case when FieldName='event_cost' then FieldValue end) as cost,
max(case when FieldName='event_loc' then FieldValue end) as Location from t
group by id

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=940326493ef7b561375953f85f65a4ea

id  Title   cost    Location
1   Event Title     10.0    Leeds
2   Another Event   15.0    London
w1jd8yoj

w1jd8yoj4#

您可以执行条件聚合:

select max(case when FieldName = 'event_name' then FieldValue end) as Title,
       max(case when FieldName = 'event_cost ' then FieldValue end) as Cost,
       max(case when FieldName = 'event_loc' then FieldValue end) as Location
from table t
group by id;
svmlkihl

svmlkihl5#

用例和聚合:

select max(case when fieldname='event_name' then FieldValue) as title,
max(case when fieldname='event_cost' then FieldValue) as cost,
max(case when fieldname='event_loc' then FieldValue) as location,
from tablename group by id

相关问题