当前位置: 代码迷 >> ASP.NET >> sql 重复记录只显示一条并排序,这个查询语句如何写
  详细解决方案

sql 重复记录只显示一条并排序,这个查询语句如何写

热度:4109   发布时间:2013-02-25 00:00:00.0
sql 重复记录只显示一条并排序,这个查询语句怎么写?
表名:Tab

ID ShopID IsHot (IsHot 是布尔类型)

1 10 0  

2 10 1 

3 30 0 

4 30 0 

5 30 0  

表Tab中字段 ShopID 值相同的只显示一条数据,至于取哪一条要根据 IsHot 的值决定,IsHot 为1时优先取,IsHot 的值相同时取最大ID 

所以上表的查询结果应该是:

ID ShopID IsHot 

2 10 1

5 30 0 

这个查询语句怎么写?


------解决方案--------------------------------------------------------
select * 
from Tab b 
where not exists(select * from biao where b.ShopID =ShopID and b.IsHot <IsHot )
order by ID desc
------解决方案--------------------------------------------------------
SQL code
select * from tab t where not exists(select 1 from tab where shopid=t.shopid and(ishot>t.ishot or ishot=t.ishot and id>t.id))
------解决方案--------------------------------------------------------
或者
SQL code
select * from(  select row_number() over(partition by shopid order by ishot desc,id desc) as rowid,*   from tab) awhere rowid = 1