3

我想获得最新的成本核算日期和产品最低成本的最后成本。

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

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

结果:

在此处输入图像描述

例如 - 对于产品 ID:200006

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

在此处输入图像描述

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

在此处输入图像描述

如何编辑我的查询以获得结果?任何帮助都感激不尽!

4

5 回答 5

4

首先,您需要获取最新日期,然后您可以找到他们的最低费用。例如

 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
于 2013-08-13T10:30:52.593 回答
1

如果您正在使用SQL Server 2005并且之后您可以使用CTE并且RANK() 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
于 2013-08-13T10:43:13.040 回答
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;
于 2013-08-13T10:29:12.303 回答
1

我认为您需要对 MAX 和 MIN 进行 2 次查询,然后将它们连接在一起以获得单行。我会使用临时表或 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
于 2013-08-13T10:32:07.603 回答
1

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

SELECT ProductName,Max(price) as MxP, '-' as minP from products 
UNION
SELECT ProductName,'-' as MxP , Min(price) as minP from products
于 2020-08-26T18:25:48.657 回答