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

SQL多行字段分组问题
表如
1 5 发 人
1 6 哈 与
1 7 一 放
2 5 虾 你
2 6 屁 股
2 8 怕 爬
8 5 富 阿
8 7 倒 萨
8 8 但 怕
结果如
1 7 一 放
2 8 怕 爬
8 8 但 怕

------解决方案--------------------
SQL code
select * from tb t where col2=(select max(col1) from tb where col1=t.col1)

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

declare @表 table 
(id int,c1 int,c2 varchar(2),c3 varchar(2))
insert into @表
select 1,5,'发','人' union all
select 1,6,'哈','与' union all
select 1,7,'一','放' union all
select 2,5,'虾','你' union all
select 2,6,'屁','股' union all
select 2,8,'怕','爬' union all
select 8,5,'富','阿' union all
select 8,7,'倒','萨' union all
select 8,8,'但','怕'

select * from @表 t
where c1=(select max(c1) from @表 where id=t.id) order by 1

/*
id          c1          c2   c3
----------- ----------- ---- ----
1           7           一    放
2           8           怕    爬
8           8           但    怕
*/

------解决方案--------------------
SELECT id, MAX(name)
FROM tb
GROUP BY id
HAVING COUNT(*) = 1
------解决方案--------------------
SQL code
select *
from tb t
where not exists(select 1 from tb where col1=t.col1 and col2>t.col2)