SQL:如何在一行中返回MAX和MIN?

时间:2013-08-13 10:14:23

标签: sql function max min

我想通过最新的成本计算日期和产品的最低成本获得最后的费用。

当我使用下面的查询时,它给出了每列的最大日期和最低成本。请参阅下面的屏幕截图。

SELECT MAX(CostingDate) AS LatestDate,
MIN(Cost) AS MinPrice,
OutletCode,
ProductID  
FROM AccountsCosting
WHERE OutletCode = 'C&T01'
GROUP BY OutletCode, ProductID

结果:

enter image description here

例如,对于productID:200006

SELECT * FROM AccountsCosting
WHERE ProductID = 200006 AND OutletCode = 'C&T01'
ORDER BY CostingDate DESC

enter image description here

我想要的是最低成本的最后成本日期(我用红色突出显示的成本日期)。即使购买日期相同2013-03-20,也应返回最低费用。

enter image description here

如何编辑查询以获得结果?任何帮助将不胜感激!

5 个答案:

答案 0 :(得分:3)

首先,您需要获取最新日期,然后您才能找到最低费用。 e.g。

 select 
    a.OutletCode, 
    a.ProductID,
     LatestDate,
    MIN(Cost) AS MinPrice

from

    (
    SELECT MAX(CostingDate) AS LatestDate,
    OutletCode,
    ProductID  
    FROM AccountsCosting
    WHERE OutletCode = 'C&T01'
    GROUP BY OutletCode, ProductID
    ) a
    left join 
    FROM AccountsCosting b
    on
    a.OutletCode=b.OutletCode
    and a.ProductID=b.ProductID  
    and a.LatestDate=b.CostingDate

    group by a.OutletCode, a.ProductID, LatestDate

答案 1 :(得分:1)

如果我理解正确,您需要最新日期的最低费用吗?!

试试这个:

SELECT CostingDate AS LatestDate,
Cost AS MinPrice,
OutletCode,
ProductID  
FROM AccountsCosting
WHERE OutletCode = 'C&T01'
and CostingDate in (SELECT MAX(CostingDate) as CostingDate FROM AccountsCosting WHERE OutletCode = 'C&T01')
and Cost in (SELECT MIN(Cost) as Cost FROM AccountsCosting WHERE OutletCode = 'C&T01' and CostingDate in (SELECT MAX(CostingDate) as CostingDate FROM AccountsCosting WHERE OutletCode = 'C&T01'))
GROUP BY OutletCode, ProductID;

答案 2 :(得分:1)

我认为你需要对MAX进行2次查询; MIN,然后加入他们一起获得你的单行。我要么使用临时表,要么使用CTE,例如

WITH CTE_Max AS
(SELECT MAX(costingDate) as latestDate,
 Oultletcode,
ProductID
FROM AccountsCosting
GROUP BY OutletCode, ProductID),

CTE_Min AS
(SELECT MIN(cost) as MinPrice,
Oultletcode,
ProductID
FROM AccountsCosting
GROUP BY OutletCode, ProductID)

SELECT * FROM CTE_Max 
JOIN CTE_Min
ON CTE_Max.outletCode=CTE_Min.outletCode
AND CTE_Max.productID=CTE_Min.productID

答案 3 :(得分:1)

如果您使用的是SQL Server 2005,之后可以使用CTERANK() OVER()

;WITH AccountCostingForOutletCode AS  (
    SELECT OutletCode, ProductID, CostingDate, Cost, 
       RANK() OVER( PARTITION BY OutletCode, ProductID ORDER BY Cost, CostingDate DESC) AS Rnk
    FROM AccountsCosting
    WHERE OutletCode = 'C&T01'
)
SELECT TOP 1 OutletCode, ProductID, CostingDate, Cost, Rnk
FROM AccountCostingForOutletCode
ORDER BY Rnk

答案 4 :(得分:0)

如果只想显示输出,可以使用一些东西

SELECT ProductName,Max(price) as MxP, '-' as minP from products 
UNION
SELECT ProductName,'-' as MxP , Min(price) as minP from products