mysql求取最后两次价格上涨趋势

SELECT DISTINCT pp.物料编码, pp.物料名称, IFNULL(pp.规格型号, '') AS 规格型号            
    , pp.物料类型, pp.单位, max1.日期 AS 最新日期, max1.单价 AS 最新价, max2.日期 AS 上一次日期        
    , max2.单价 AS 上一次价        
    , (max1.单价 - max2.单价) / NULLIF(max2.单价, 0) AS 涨幅        
    , max3.日期 AS 上二次日期, max3.单价 AS 上二次价, min2.日期 AS 最初日期, min2.单价 AS 最初价        
FROM dbo.PurchasePrice pp            
    LEFT JOIN (        
        SELECT 物料编码, 日期, 单价    
        FROM dbo.PurchasePrice max11    
        WHERE 序号 IN (    
            SELECT MAX(序号) AS Expr1
            FROM dbo.PurchasePrice max12
            WHERE max11.物料编码 = 物料编码
        )    
    ) max1        
    ON pp.物料编码 = max1.物料编码        
    LEFT JOIN (        
        SELECT 物料编码, 日期, 单价    
        FROM dbo.PurchasePrice max21    
        WHERE 序号 IN (    
            SELECT MAX(序号) - 1 AS Expr1
            FROM dbo.PurchasePrice max22
            WHERE max21.物料编码 = 物料编码
        )    
    ) max2        
    ON pp.物料编码 = max2.物料编码        
    LEFT JOIN (        
        SELECT 物料编码, 日期, 单价    
        FROM dbo.PurchasePrice max31    
        WHERE 序号 IN (    
            SELECT MAX(序号) - 2 AS Expr1
            FROM dbo.PurchasePrice max32
            WHERE max31.物料编码 = 物料编码
        )    
    ) max3        
    ON pp.物料编码 = max3.物料编码        
    LEFT JOIN (        
        SELECT 物料编码, 日期, 单价    
        FROM dbo.PurchasePrice min21    
        WHERE 序号 IN (    
            SELECT MIN(序号) AS Expr1
            FROM dbo.PurchasePrice min22
            WHERE min21.物料编码 = 物料编码
        )    
    ) min2        
    ON pp.物料编码 = min2.物料编码    

 

posted @ 2021-01-02 00:56  爱学习的小猫咪  阅读(149)  评论(0编辑  收藏  举报