日期:2014-05-17  浏览次数:20409 次

分组查询碰到的问题,, ############################ 100% 结贴
表的列数比较多, 我就贴三列出来 
Asid           State    CreateUid   
        
714   未得标 1111
715 分配完成 660007
716 未得标 660008
717 未得标 660007
718 未得标 660084
719 未得标 660129
720 未得标 660007
721 未得标 660009
722 未得标 660117
723 分配完成 660125
724 分配完成 660037
725 未得标 660010
726 未得标 666888
727 分配完成 660008
728 分配完成  660009
729 未得标 660007
730 未得标 660008
731 未得标 660065
732 分配完成 660007

现在需要查询的结果是, 按CreateUid 分组,如果只有一条记录在查询范围内,如果有1条记录以上就只查询第二条。
;with ct as  (select row_number() over (partition by createUid order by asid) num ,* from AuctionSell)
select * from   ct
 where num=2  or num=(select max(num) from ct b where createuid=ct.createuid ) AND NUM=1 

上面是我自己写的查询语句,能够达到查询要求, 但有两个小问题,请教下各位大牛,,,
问题一,表中只有2000条不到的数据,不知道是不是用了 or 的原因,查询很慢。各位有没有更好的查询。
第二个, 弱弱的问一句,为什么我改成下面这样会报错,提示对象名  'ct' 无效。?
select * from   
(select row_number() over (partition by createUid order by asid) num ,* from AuctionSell) ct
 where num=2  or num=(select max(num) from ct b where createuid=ct.createuid ) AND NUM=1 

------解决方案--------------------
;with ct as  
(
select row_number() over(partition by createUid order by asid) row_id
   ,count(*) over(partition by createUid) row_count,* 
from AuctionSell
)
select * 
from ct
where row_id=case when row_count>1 then 2 else 1 end