SQL求助:对一个字段里重复数据,取出不同数据的前两个

表orderdate如下 求取出 o_id customer 1 bush 3 bush 2 carter 6 carter 5 adams 就是每个custmer取出前两个
我的目的是为了在一个字段里相同的数据只取出前2个其他的忽略掉

第1个回答  2013-02-26
我来写个长长的相当复杂的。
select IDENTITY(int,1,1)as xh,customer into #temp1 from orderdate group by customer having count(*)>1
select * into #temp2 from orderdate where customer in (select customer from #temp1 )
select * into #temp3 from #temp2 left join #temp1 where #temp2. customer =#temp1.customer
--先将重复的取出来
create table B(
o_id int,
custmer varchar(255)
)
declare
@X int,
@Y int
select @X=min(xh) from #temp1
select @Y=max(xh) from #temp1
while @X<=@Y
insert into B
select top 2 o_id,custmer from #temp3 where xh=@X
set @X=@X+1
end
select * from B
drop table #temp1
drop table #temp2
drop table #temp3
drop table B
第2个回答  2013-02-26
select * from (
select *, ROW_NUMBER() over(PARTITION BY customer order by customer ) dd from orderdate) as ff where dd<=2追问

PARTITION BY oracle函数? 能介绍下思路吗 不胜感激

追答

这条语句是在SQL中使用的,你的编译环境是oracle?

追问

我在mysql下查询,报错
SELECT *, ROW_NUMBER() over(PARTITION BY customer ORDER BY customer )dd FROM orderdate这句话报错

追答

哦,oracle不支持ROW_NUMBER() 这个函数,我再想想。

第3个回答  2013-02-26
select Customer from Orders
where Customer='Adams' or Customer='Carter' or OrderPrice>=700
order by Customer desc
我暂时只能想到这样取巧的方法,我也试过了是可以的。不知道是不是你想要的结果。