首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

取一个结果集中的相同字段唯一值,求高手看下~该如何处理

2012-06-11 
取一个结果集中的相同字段唯一值,求高手看下~先举例子id(唯一)bazcname111111小明211112小明311113小明422

取一个结果集中的相同字段唯一值,求高手看下~
先举例子
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 allselect 2,1111,2,'小明' union allselect 3,1111,3,'小明' union allselect 4,2222,1,'小丽' union allselect 5,2222,2,'小丽' union allselect 6,3333,1,'小红'select * from test awhere 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递增排序)twhere px=1--取出每个分组的排序为1(px=1)的数据 

热点排行