首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

分组查询碰到的有关问题, # 100% 结贴

2013-12-28 
分组查询碰到的问题,, ############################ 100% 结贴表的列数比较多, 我就贴三列出来 AsidState

分组查询碰到的问题,, ############################ 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

热点排行