【问题标题】:turn the distinct value of columns into a rows postgres将列的不同值转换为行 postgres
【发布时间】:2018-04-16 16:48:46
【问题描述】:

我有一个类似的架构:

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

行名包含多个值:agenamebirthdayjobage 我想把它转换成这个:

[ad_id] .   [name]  .      [age] .      [birthday] .    [job]
         [valueofname] [valueofname] [valueofname] [valueofname]

我已经完成了每一行的查询:

select * from where name='name'
select * from where name='age'
select * from where name='job'

我看到了例子SQL Server : Columns to Rows。但这与我的问题相反。

您对在性能方面进行可扩展查询有什么建议吗?

【问题讨论】:

  • @SandeshGupta 谢谢你,但我怎样才能在不创建视图的情况下进行选择??
  • 您使用的是 MySQL 还是 SQL Server?
  • @GordonLinoff 我在我的应用程序中同时使用 mysql 和 postgres,但这里的案例在我的 postgres 中

标签: sql postgresql pivot crosstab


【解决方案1】:

您可以使用条件聚合:

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;

在 SQL Server 中,您也可以使用 pivot 执行类似的操作。

【讨论】:

  • 谢谢,但这里的问题是我有一个字符串值,所以最大值和总和不起作用
  • @a_horse_with_no_name 如果我必须做 ae 怎么办?
  • @Medone 。 . .您可以将该值转换为您认为合适的任何类型。数据库中的数据存储为字符串。但是,对于检索值(假设每个 ad_id 一个),上述方法很好。
  • @a_horse_with_no_name 如果没有返回行将其替换为 NULL 而不是 "" 会怎样?因为数据库中缺少某些名称
猜你喜欢
  • 2020-11-14
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多