例如,如果我们有值:
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?
什么都不好(我所期待的)
还有其他办法吗?
答案 0 :(得分:3)
您可以使用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
答案 1 :(得分:2)
这是使用子查询的另一种方法。请注意,两个答案都会按字母顺序将类别值提供给第一个用户名,即Allen将获得cs和Bill ts。
select a.username,b.category from
foo a
left join
(select category,min(username) as username from foo group by category) b
on b.username = a.username
order by a.category,a.username
[编辑]如果你想分配到你表格中的第一个实例(即返回你在问题中提出的内容),你可以这样做:
with foobar as
(select username,category, row_number() over() as rownum from foo )
select a.username,coalesce(b.category,'') as category from
foobar a
left join
(select category,min(rownum) as rownum from foobar group by category) b
on b.rownum = a.rownum
order by a.rownum,a.username