sql - 发送数据以显示为列

标签 sql postgresql pivot postgresql-9.1

在给定的表中;我正在查询以显示某些列,如下所示

select an.animals_key,           
       an.anim_name,
       an.sex,
       an.date_of_birth,
       tt.trait_key,            
       --case when tt.trait_key = 152 then 'Left Eye Pigment'
            --when tt.trait_key = 153 then 'Right Eye Pigment' end as trait_key,
       tt.trait_value,
       tt.observation_date

 from animals an
 join traits tt on tt.soc_code = an.soc_code and tt.animals_key = an.animals_key and tt.trait_key in (152,153)
 where an.soc_code = 'AUHF' limit 10

此查询为我生成了以下数据。

enter image description here

有什么办法,我可以将 152 作为一列,将 153 作为一列,这样我就可以将所有特征值放在这些列中

最佳答案

如果列数始终是预定义的(在您的情况下为 152、153),您可以进行条件聚合

select an.animals_key, an.anim_name, an.sex, an.date_of_birth, tt.observation_date
       min(case when tt.trait_key = 152 then tt.trait_value end) "152",
       min(case when tt.trait_key = 153 then tt.trait_value end) "153"
  from animals an join traits tt 
    on tt.soc_code = an.soc_code 
   and tt.animals_key = an.animals_key
   and tt.trait_key in (152, 153)
 where an.soc_code = 'AUHF'
 group by an.animals_key, an.anim_name, an.sex, an.date_of_birth, tt.observation_date

关于sql - 发送数据以显示为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42546546/

相关文章:

javascript - 使用 pg 管理从 nodejs 到 postgres 的许多连接

sql - 转置 PostgreSQL 表或聚合函数什么都不做

Sql Server - 将多个查询合并为一个

php - 查询是否正确,除了第 9 行之外的所有行

mysql - SQL 查询从一个表获取所有记录并连接到另一个表,包括任何其他唯一记录

mysql - 从多对多中选择问题

postgresql - 将表列更改为 int(9) UNSIGNED ZEROFILL NOT NULL

ruby-on-rails - 公寓 gem 的外键问题

SQL 如何将两列数据转换为不同的列?

sql - 如何在sql中将两行合并为一行?