SQL取出每个产品的Top n 条记录

1.创建表结构和数据

ExpandedBlockStart.gif 创建表和数据
Create   Table  Product  -- 产品表
(
ProductID 
Int   Identity ( 1 , 1 Primary   key -- 产品ID
ProductName  NVarchar ( 100 Not   Null -- 产品名称
ProductPrice  Int   Not   Null -- 价格
)
GO

Create   Table  ProductOrder  -- 产品订单
(
OrderID 
Int   Identity ( 1000 , 1 Primary   key ,
ProductID 
Int ,
Quantity 
Int , -- 数量
amount  Int , -- 金额
OrderDateTime  DateTime   Not   Null   -- 下单时间
)
Alter   Table  ProductOrder
Add   Constraint  FK_ProductOrder_ProductID  Foreign   Key (ProductID)
References  Product(ProductID)
GO


Insert   Into  Product
Values ( ' 黄金 ' , 389.8 )

Insert   Into  Product
Values ( ' 白银 ' , 8.9 )

Insert   Into  ProductOrder
Values ( 1 , 10 , 3890 , GetDate ())

Insert   Into  ProductOrder
Values ( 2 , 1000 , 8900 , GetDate ())

Insert   Into  ProductOrder
Values ( 1 , 150 , 389.8 * 150 , ' 2012-12-21 ' )

Insert   Into  ProductOrder
Values ( 1 , 60000 , 388 * 60000 , ' 2011-10-1 ' )

Insert   Into  ProductOrder
Values ( 2 , 10000 , 88950 , GetDate ())

Insert   Into  ProductOrder
Values ( 2 , 1000 , 8850 , GetDate ())

Insert   Into  ProductOrder
Values ( 2 , 4000 , 32850 , GetDate ())

Select   *   from  Product
Select   *   from  ProductOrder

2.取出每个产品的前2条记录

   2.1 使用ROW_NUMBER() 进行排位分组

 

Select  T.OrderID, P.ProductName, T.Quantity, T.Amount, T.OrderDateTime
From  Product P
Left   Join  
(
Select  Row_Number()  over (Partition  By  ProductID  Order   by  OrderDateTime  Desc As  RowID,
OrderID, ProductID,Quantity, Amount,OrderDateTime
From  ProductOrder
) T 
On  T.ProductID  =  P.ProductID
Where  T.RowID < 3

   2.2 使用Cross Apply

 

Select  T.OrderID, P.ProductName, T.Quantity, T.Amount, T.OrderDateTime
From  Product P
Cross  Apply
(
Select   Top   2   *   from  ProductOrder O Where  O.ProductID  =  P.ProductID
Order   By  OrderDateTime  Desc
As  T

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/chinabc/archive/2011/03/11/1980632.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值