CustomerID | DateTime | ProductName | Price |
C001 | 2014-11-20 16:02:59 123 | PVC | 100 |
C001 | 2014-11-19 16:02:59 123 | POM | 310 |
C001 | 2014-10-18 16:02:59 123 | HDPE | 400 |
C001 | 2014-10-17 16:02:59 123 | PET | 200 |
C002 | 2014-09-17 16:02:59 123 | EVA | 300 |
C002 | 2014-09-20 16:02:59 123 | PET | 210 |
C003 | 2014-11-20 16:02:59 123 | HDPE | 600 |
C003 | 2014-08-20 16:02:59 123 | POM | 300 |
C003 | 2014-08-10 16:02:59 123 | EVA | 310 |
这是我面试时遇到的一道题目。
如图所示,CustomerID和DateTime是主键,求每个CustomerID每个月最高Price的订单,以及商品名字。
也就是得到如下结果:
CustomerID | Month | ProductName | MaxPrice |
C001 | 11 | POM | 310 |
C001 | 10 | HDPE | 400 |
C002 | 9 | EVA | 300 |
C003 | 11 | HDPE | 600 |
C003 | 8 | POM | 300 |
怎么写SQL呢?
我的思路是这样的,不知道对不对。
Select T2.CustomerID,T2.Month,Tbl.ProductName,T2.MaxPrice
From
(
Select CustomerID,Datetime.Month Month,MaxPrice
From Tbl
Group by Tbl.CustomerID,Datetime.Month
) T2
Inner Join Tbl
On T2.CustomerID = Tbl.CustomerID
And T2.Month = Tbl.DateTime.Month
And T2.MaxPrice = Tbl.Price