1

假设我有一个名为 [ProductPriceHistory] ​​的表,如下所示:

HistoryID..ProductCode..EffectDate..Price..IsActive...ProductName
1----------11------------1 Jan 09--------100--------true--------AAA
2---------11------------1 2 月 9 日--------150--------真实--------AAA
3----------11-----------1 Mar 09--------200--------假-----AAA
4----------22------------1 Jan 09--------150--------true-----BBB
5----------22-----------1 2 月 9 日-------200-------真--------BBB
6------------22------------1先生09--------250--------真------- AAA

我怎样才能找到所有活跃产品在最近日期的最终状态?

也就是说,我的查询将找到该行:

6------------22------------1先生09--------250--------真------- AAA
4

4 回答 4

2
select * from ProductPriceHistory p1
where EffectDate = 
(select max(EffectDate) from ProductPriceHistory p2
where p1.ProductCode = p2.ProductCode and p2.EffectDate<=getdate())
于 2009-06-09T15:49:55.867 回答
1

获取给定产品代码的值使用:

DECLARE @ProcuctCode  int
SET @ProductCode=11

SELECT
    h.* 
    FROM ProductPriceHistory h
        INNER JOIN (SELECT
                        ProductCode
                            ,MAX(EffectDate) AS MaxEffectDate
                        FROM ProductPriceHistory
                        WHERE ProductCode=@ProductCode
                            AND IsActive='true'
                        GROUP BY ProductCode
                   ) dt ON h.ProductCode=dt.ProductCode AND h.EffectDate=dt.MaxEffectDate
    WHERE h.ProductCode =@ProductCode

查找所有产品使用:

SELECT
    h.* 
    FROM ProductPriceHistory h
        INNER JOIN (SELECT
                        ProductCode
                            ,MAX(EffectDate) AS MaxEffectDate
                        FROM ProductPriceHistory
                        WHERE IsActive='true'
                        GROUP BY ProductCode
                   ) dt ON h.ProductCode=dt.ProductCode AND h.EffectDate=dt.MaxEffectDate
     ORDER BY h.ProductCode
于 2009-06-09T16:01:29.863 回答
1

你没有完全指定——也许@tekBlues'查询是你想要的,或者也许:

SELECT * FROM ProductPriceHistory t1
WHERE t1.EffectDate =
  (SELECT MAX(t2.EffectDate)
   FROM ProductPriceHistory t2
   WHERE t2.IsActive=true)
  AND t1.IsActive=true
于 2009-06-09T15:51:34.803 回答
0

假设 ProductCode 和 EffectDate 唯一标识一行,您可以这样做:

SELECT *
  FROM productpricehistory
     , (SELECT productcode
             , MAX(effectdate) effectdate
          FROM productpricehistory
         GROUP BY productcode) maxhistory
 WHERE productpricehistory.productcode = maxhistory.productcode
   AND productpricehistory.effectdate = maxhistory.effectdate
   AND IsActive = TRUE;

如果 ProductCode 和 EffectDate 不能唯一标识一行,那么您可能希望使用 HistoryId 而不是 EffectDate,如果我们可以假设 HistoryId 是唯一的并且增加的 HistoryId 也意味着增加的 EffectDate。

编辑:我意识到我对待活动的方式与你不同 - 我假设 IsActive 仅适用于特定的 EffectDate,但我看到你通过将其“IsActive”设置为 false 来停用整个产品。我相应地进行了更新,假设您随后可以通过创建一个 IsActive = true 的新行来激活产品。

于 2009-06-09T15:52:19.890 回答