簡體   English   中英

一行中最小和最大行的SQL值

[英]SQL values for min and max rows in one row

我有一張價格變動表,我需要獲取初始價格和最新價格。 換句話說,我想在每種產品的一行中顯示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都不會重復。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM