读书人

sql 重复记录只显示一条并排序这个查

发布时间: 2012-08-21 13:00:21 作者: rapoo

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 

读书人网 >asp.net

热点推荐