比如有分类表category。表中有A,B,C,D四个分类
商品表product中有一人categoryId与category关联。
请问:如何人product表中获取每个分类的第一条数据呢?
CREATE table Cate (CateID int, CateName Nvarchar(20)); CREATE table Product (ProductID int, CateID int, ProductName Nvarchar(20)); INSERT Cate values (1,'DemoA'), (2,'DemoB'), (3,'DemoC'), (4,'DemoD') INSERT PRODUCT values (1,1,'PA'), (2,3,'PB'), (3,2,'PC'), (4,2,'PD'), (5,4,'PE'), (6,3,'PF'), (7,1,'PG'), (8,4,'PH') SELECT * FROM product; /* ProductID CateID ProductName 1 1 PA 2 3 PB 3 2 PC 4 2 PD 5 4 PE 6 3 PF 7 1 PG 8 4 PH */
--方法一: Select t.CateID,t.ProductID,t.ProductName From (Select CateID,ProductID,ProductName, Row_Number() over(Partition By CATEID Order by productid Asc) RowID From PRODUCT ) t WHERE t.RowID=1 --方法二: SELECT CateID,ProductID,ProductName FROM PRODUCT T WHERE productID in ( SELECT top 1 productID FROM PRODUCT WHERE cateid=T.cateid order by cateID asc ) /* CateID ProductID ProductName 1 1 PA 2 3 PC 3 2 PB 4 5 PE */
这个好像不太容易,我先自己试试!
选取ID最前面的一条
select * from product where id in(select min(id) from product group by categoryID)
选取ID最后面的一条
select * from product where id in(select max(id) from product group by categoryID)
问题实在描述的不清晰。。。
分组查询group by ,条目数限制 limit 数目;
效率效率怎么样,方法二的效率好像不怎么样。一还没试过