postgresql - 在 PostgreSQL 中抑制重复的列值?

标签 postgresql

例如,如果我们有以下值:

username             Category
-------------------- ----------
Brian                cs
Tom                  cs
Joe                  cs
Allen                cs
Bill                 ts
Steven               ts
Fred                 ts
Ted                  ts

我需要一个输出作为

username             Category
-------------------- ----------
Brian                cs
Tom                  
Joe                  
Allen                
Bill                 ts
Steven               
Fred                 
Ted      

我试过

1) T-SQL How to select rows without duplicate values from one column?

2) http://www.rajapet.com/2010/04/suppressing-repeated-column-value-in.html

3) How to select records without duplicate on just one field in SQL?

没有什么效果很好(我所期望的)

还有其他办法吗?

最佳答案

您可以使用 window function为此:

select username, 
       case when rn = 1 then cat else '' end as category
from (
   select username, 
          category as cat, 
          row_number() over (partition by category order by username) as rn
   from the_table
) t
order by cat, username;

SQLFiddle:http://sqlfiddle.com/#!15/423ed/4

关于postgresql - 在 PostgreSQL 中抑制重复的列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28108682/

相关文章:

ruby-on-rails - 在 Heroku 上部署失败并出现 PostgreSQL ActionView::Template::Error

postgresql - 为什么 Aurora Postgres 12.4 不能将其实例类从 db.r5.xlarge 更改为 db.r6g.4xlarge?

ruby - 使用 pg gem 显示 postgres sql 结果

postgresql - Postgres word_similarity 不比较单词

java - 更改表结构但 hibernate 不更新它

database - 压缩表 - Postgresql

sql - Postgresql 加入选择语句

postgresql - postgres的密码

sql - 如何在 postgresql 中获取唯一约束的名称?

postgresql - Yii2:SQL 查询中的函数