我有一张价格变化的表格,我需要获得初始价格和最新价格。换句话说,我想在一行中为每个产品显示 min(StartDate) 和 max(StartDate) 的价格值。
表结构很简单:
ProductID, StartDate, Price
期望的结果是
ProductId, StartDate, InitialPrice, LatestDate, LatestPrice
我有一张价格变化的表格,我需要获得初始价格和最新价格。换句话说,我想在一行中为每个产品显示 min(StartDate) 和 max(StartDate) 的价格值。
表结构很简单:
ProductID, StartDate, Price
期望的结果是
ProductId, StartDate, InitialPrice, LatestDate, LatestPrice
WITH latestPrice AS
(
SELECT ProductID, StartDate, Price,
ROW_NUMBER() OVER (PArtition BY ProductID ORDER BY StartDate DESC) rn
FROM TableName
)
, initalPrice AS
(
SELECT ProductID, StartDate, Price,
ROW_NUMBER() OVER (PArtition BY ProductID ORDER BY StartDate ASC) rn
FROM TableName
)
SELECT a.ProductID,
b.StartDate,
b.Price InitalPrice,
c.StartDate LatestDate,
c.Price LatestPrice
FROM (SELECT DISTINCT ProductID FROM tableName) a
INNER JOIN initalPrice b
ON a.ProductID = b.ProductID AND b.rn = 1
INNER JOIN latestprice c
ON a.ProductID = c.ProductID AND c.rn = 1
(SELECT x.ProductId, x.MinStartDate, x.MinPrice, y.MaxStartDate, y.MaxPrice FROM (SELECT a.ProductId, a.MinStartDate, b.Price AS MinPrice FROM (SELECT ProductId, MIN(StartDate) AS MinStartDate FROM Products GROUP BY ProductId) a INNER JOIN Products b ON a.ProductId = b.ProductId AND a.MinStartDate = b.StartDate) x INNER JOIN (SELECT a.ProductId, a.MaxStartDate, b.Price AS MaxPrice FROM (SELECT ProductId, MAX(StartDate) AS MaxStartDate FROM Products GROUP BY ProductId) a INNER JOIN Products b ON a.ProductId = b.ProductId AND a.MaxStartDate = b.StartDate) y ON x.ProductId = y.ProductId
免责声明:这是凭记忆,如果这不完全准确,我深表歉意。并且它假定 StartDate 是一个日期时间或不为每个 productId 重复。
希望这可以帮助。