douba1067 2018-04-16 08:59
浏览 304

连续多个条件(如果不存在)返回NULL postgresql

I have a schema like:

[ad_id] .  [name] . [valueofname]
 1 .        name .    "brian"
 1 .        age  .    "23"
 2 .        job  .    "IT"
 2 .        name .    "Jack" 

the row name contains multiple values : age , name, birthday, job, age I'd like to convert it into this:

[ad_id] .      [name]  .       [age] .              [birthday] .    [job]
[valueofad_id][valueofname] [valueofnameofage] [valueofnameofbirth] [valueofnameofjob]

I did this query selection below to fix it , so in my program i must get the result where ad_id='xxxx' for each when name='name or age or birthday or job '

Some ad_id have not all the names , as you may see below the schema the ad_id= 1 has just the name and age but not the job so i want when the job not found it returns a 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条回答 默认 最新

  • du5114 2018-04-16 10:55
    关注

    To flatten the records for all ad_ids, use:

    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;
    

    To get the results for a single ad_id, add a where clause:

    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;
    

    Note: If there are no rows with ad_id = 'xxx' then this will return no rows.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题