读书人

请问:查询表中每个类别的第一条记录的

发布时间: 2012-01-13 22:43:29 作者: rapoo

请教:查询表中每个类别的第一条记录的sql。内详
请教一段SQL语句:
Table1有多个列,其中两列是:class1,class2
class1 class2 col3,col4 .....
a a1 * *
a a2
a a3
b b1
b b2
我只想选出每个Class1中的第一条记录,该如何写sql
结果应该是:
class1 class2 col3 col4 .....
a a1 * *
b b1 * *
多谢大家。

[解决办法]
select t.* from table1 t where not exists(select 1 from table1 where class1=t.class1 and class2 <t.class2)

select t.* from table1 t where t.class2=(select min(class2) from table1 where class1=t.class1)
[解决办法]
select a.* from tb a,
(select class1,min(class2) as class2 from tb group by class1) b
where a.class1 = b.class1 and a.class2 = b.class2
[解决办法]
table1
class1 class2 col3,col4 .....
a a1 * *
a a2
a a3
b b1
b b2
select class1,min(class2)class2,col3= '* ',col4= '* 'from tbale1 group by class1
---或
select class1,(select top 1 class2 from table1 b where b.class1=a.class1)class2,col3= '* ',col4= '* 'from tbale1 a group by class1
[解决办法]
楼主提的问题有语病,不清

我只想选出 --------每个Class1中的第一条记录------ ,该如何写sql
结果应该是:
假如表是这样
class1 class2 col3,col4 .....
a a5 * *
a a2
a a3
b b1
b b2
那么根据楼主提的问题所要结果应是这样
class1 class2 col3,col4 .....
a a5 * *
b b1
而不是
class1 class2 col3,col4 .....
a a1 * *
b b1
对吧

上面两位朋友都做成最后一解答案了


[解决办法]
2005的:
select class1,class2,col3,col4, row_number() over(partition by class1 order by class1 desc) rownum from tabl2 where rownum=1

读书人网 >SQL Server

热点推荐