关于SQL Server2005的查询语句

来源:百度知道 编辑:UC知道 时间:2024/05/22 03:19:44
假设有一张表,表中有一个叫字段叫做“城市”,表中一共有5个城市,这张表包含100条数据,也就是说没个城市有200条数据。
现在需要一条SQL语句,查出没个城市的前5条数据,也就是说要查出25条数据,分别属于5个城市。
如果我没有说明白,可以看一下我附加的数据表:
create table MyTable
(
id int identity primary key,
city varchar(5) not null,
shopName varchar(20) not null, -- 只是用来说明城市中的商铺名
)

insert into MyTable values ('A','shopA')
........ -- 省略城市A的其他商铺
insert into MyTable values ('B','shopB')
........ -- 省略城市B的其他商铺
insert into MyTable values ('C','shopC')
........ -- 省略城市C的其他商铺
insert into MyTable values ('D','shopD')
........ -- 省略城市D的其他商铺
insert into MyTable values ('E','shopE')
........ -- 省略城市E的其他商铺

* * * * * * * * * *

我想要的结果就是通过一条语句,查出每个城市的5家商铺。一个是25个商铺
注:这个数据库没写全,可以增加字段,比如说,增加一个销售量字段,来设置查询条件。

SELECT a.* FROM mytable a
WHERE a.id IN (SELECT TOP 5 id FROM mytable WHERE city = a.city)
ORDER BY a.city

销售量等作为其他判断条件的语句可写在括号里的where后,不影响其查询

MS SQL2005\2008实现方法
--------------------
select B.*
from
(select distinct City from MyTable) A
cross apply
(select top 5 * from MyTable where City=A.City) B