我有一张表样本,其中包含产品价格样本。请注意升序日期顺序。
+----+------------+-------+-------+-------------+
| Id | Product_Id | Price | Status| Date |
+----+------------+-------+-------+-------------+
| 1 | 1 | 400 | 0 | 1404656325 |
| 2 | 2 | 300 | 0 | 1404657325 |
| 3 | 3 | 100 | 0 | 1404658325 |
| 4 | 1 | 400 | 0 | 1404659325 |
| 5 | 2 | 300 | 0 | 1404660325 |
| 6 | 3 | 100 | 1 | 1404661325 |
| 7 | 1 | 500 | 1 | 1404662325 |
| 8 | 2 | 500 | 0 | 1404663325 |
| 9 | 3 | 500 | 1 | 1404664325 |
+----+------------+-------+-------+-------------+
我有兴趣对Product_Id进行分组,以便我列出唯一的产品ID以及最新价格(即最大日期)。
这有点是经典的每组最大n问题,但另外我还想要一个数字列,显示从最早的日期开始, Status 列的连续行数是多少
因此,考虑到上面的示例表,我最终应该
+------------+-------+-----------------+
| Product_Id | Price | SameStatus |
+------------+-------+-----------------+
| 1 | 500 | 1 |
| 2 | 500 | 3 |
| 3 | 500 | 2 |
+------------+-------+-----------------+
我希望很清楚我想要实现的目标,并且有一个友好的人愿意指导我。
答案 0 :(得分:1)
这应该有效。
该方法使用ROW_NUMBER()
;WITH Samples (Id, Product_Id, Price, [Status], [Date]) AS
(
SELECT 1, 1, 400, 0, 1404656325 UNION ALL
SELECT 2, 2, 300, 0, 1404657325 UNION ALL
SELECT 3, 3, 100, 0, 1404658325 UNION ALL
SELECT 4, 1, 400, 0, 1404659325 UNION ALL
SELECT 5, 2, 300, 0, 1404660325 UNION ALL
SELECT 6, 3, 100, 1, 1404661325 UNION ALL
SELECT 7, 1, 500, 1, 1404662325 UNION ALL
SELECT 8, 2, 500, 0, 1404663325 UNION ALL
SELECT 9, 3, 500, 1, 1404664325
)
,NumberingLogic AS
(
SELECT *
,SameStatus = ROW_NUMBER() OVER (PARTITION BY Product_Id, [Status] ORDER BY [Date])
,MaxPrice = ROW_NUMBER() OVER (PARTITION BY Product_Id ORDER BY [Date] DESC)
FROM Samples
)
SELECT Product_Id
,Price
,SameStatus
FROM NumberingLogic
WHERE MaxPrice = 1
PS。 您的日期如何工作对我来说有点不清楚,但我已经用它们来订购