如果不存在,则行上的多个条件返回NULL postgresql

时间:2018-04-16 08:59:49

标签: sql postgresql go

我有一个类似的架构:

[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}}或birthdayjob'

有些ad_id没有全部名称,因为您可能会在模式下方看到ad_id= 1只有nameage而不是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;

1 个答案:

答案 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'行,则不会返回任何行。