我有一个类似的架构:
[ad_id] . [name] . [valueofname]
1 . name . "brian"
1 . age . "23"
2 . job . "IT"
2 . name . "Jack"
行名称包含多个值:年龄,姓名,生日,工作,年龄我想将其转换为:
[ad_id] . [name] . [age] . [birthday] . [job]
[valueofad_id][valueofname] [valueofnameofage] [valueofnameofbirth] [valueofnameofjob]
我在下面执行了此查询选择以修复它,所以在我的程序中,我必须在ad_id
='name
或{{name
='age
或{{ 1}}或birthday
或job
'
有些ad_id
没有全部名称,因为您可能会在模式下方看到ad_id= 1
只有name
和age
而不是job
所以我想在找不到工作时返回NULL
[ad_id] . [name] . [valueofname]
1 . name . "brian"
1 . age . "23"
2 . job . "IT"
2 . name . "Jack"
select ad_id,
max(case when name = 'name' and ad_id='xxx' then valueofname end) as name,
max(case when name = 'age' and ad_id='xxx' then valueofname end) as age,
max(case when name = 'birthday' and ad_id='xxx' then valueofname end) as birthday,
max(case when name = 'job' and ad_id='xxx' then valueofname end) as job
from t
group by ad_id;
答案 0 :(得分:0)
要展开所有 ad_id
的记录,请使用:
select ad_id,
max(case when name = 'name' then valueofname end) as name,
max(case when name = 'age'then valueofname end) as age,
max(case when name = 'birthday' then valueofname end) as birthday,
max(case when name = 'job' then valueofname end) as job
from t
group by ad_id;
要获得单个ad_id
的结果,请添加where
子句:
select ad_id,
max(case when name = 'name' then valueofname end) as name,
max(case when name = 'age'then valueofname end) as age,
max(case when name = 'birthday' then valueofname end) as birthday,
max(case when name = 'job' then valueofname end) as job
from t
where ad_id = 'xxx'
group by ad_id;
注意:如果没有ad_id = 'xxx'
行,则不会返回任何行。