日期:2014-05-18  浏览次数:20522 次

取一个结果集中的相同字段唯一值,求高手看下~
先举例子
id(唯一) ba zc name
1 1111 1 小明
2 1111 2 小明
3 1111 3 小明
4 2222 1 小丽
5 2222 2 小丽
6 3333 1 小红
。。。后面还有好多类似的数据
如图id 是唯一值 ba和zc 也可以联合确定一条数据
相同的ba列 有可能有多条数据但是ZC不一样
现在我想求出来这个结果集中
ba相同的取出一条数据
得出
1 1111 1 小明
4 2222 1 小丽
6 3333 1 小红
。。。
这个结果集来
求高手帮忙解答一下 不胜感激~ 最好有注释。。本人水平较低

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([id] int,[ba] int,[zc] int,[name] varchar(4))
insert [test]
select 1,1111,1,'小明' union all
select 2,1111,2,'小明' union all
select 3,1111,3,'小明' union all
select 4,2222,1,'小丽' union all
select 5,2222,2,'小丽' union all
select 6,3333,1,'小红'

select * from test a
where a.zc=(select MIN(zc) from test b where a.ba=b.ba)
/*
id    ba    zc    name
--------------------------------
1    1111    1    小明
4    2222    1    小丽
6    3333    1    小红
*/

------解决方案--------------------
SQL code
select * from test t where not exists(select 1 from test whereba=t.ba  and zc<t.zc)

------解决方案--------------------
SQL code
select id,ba,zc,name from(
select px=ROW_NUMBER()over(partition by ba order by zc asc),
* from test--这个查询返回的是按照ba分组,zc递增排序
)t
where px=1--取出每个分组的排序为1(px=1)的数据