读书人

SQL中Select疑难有关问题(distinct co

发布时间: 2012-02-13 17:20:26 作者: rapoo

SQL中Select疑难问题(distinct column)
数据库中有Table History
表中有两个字段 HistoryId,StuId

select HistoryId,StuId
from History

输出结果:
HistoryId StuId
1 23
2 23
3 45
4 89

请问如何写SQL能实现下面的输出结果

HistoryId StuId
1 23
3 45
4 89

如果StuId有复数行的话,只取一行

望高手赐教



[解决办法]
select min(HistoryId ) as HistoryId , StuId from History group by StuId

*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码)

最新版本:20070212

http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html
[解决办法]
select min(HistoryId) as HistoryId, StuId from History group by StuId
[解决办法]
create table History(HistoryId int, StuId int)
insert History select 1, 23
union all select 2, 23
union all select 3, 45
union all select 4, 89

select * from History as tmp
where not exists(select 1 from History where StuId=tmp.StuId and HistoryId <tmp.HistoryId)

--result
HistoryId StuId
----------- -----------
1 23
3 45
4 89

(3 row(s) affected)

读书人网 >SQL Server

热点推荐