没有分组到最新日期

时间:2013-11-14 08:49:30

标签: sql database join sql-server-2008-r2

我有3张表如下:

BarcodeGroupMap

enter image description here

CategoryMaster

enter image description here

ProductMaster:

enter image description here

从这3张表中我做了以下查询:

select bgm.BarcodeItem,
cm.CategoryID,cm.CategoryName,pm.ProductName,pm.ProductID,bgm.EffectFrom,bgm.Groups
from BarcodeGroupMap bgm,CategoryMaster cm,ProductMaster pm where
bgm.ProductID=pm.ProductID  and bgm.categoryID=cm.CategoryID

此查询结果如下:

enter image description here

现在,正如我们在查询结果中看到的那样,条形码正在重复,

根据 Barcodegroupmap 表中最新的 Createddate ,我只想展示一个条形码。

为此我做了以下查询:

select bgm.BarcodeItem,
cm.CategoryID,cm.CategoryName,pm.ProductName,pm.ProductID,bgm.EffectFrom,bgm.Groups
from BarcodeGroupMap bgm,CategoryMaster cm,ProductMaster pm where
bgm.ProductID=pm.ProductID  and bgm.categoryID=cm.CategoryID and
bgm.BarcodeItem= select BarcodeItem from  BarcodeGroupMap bm1  where
CreatedDate=  (select top 1 CreatedDate from  BarcodeGroupMap bm2  
)order by bm1.BarcodeItem

但它没有给我正确的结果。

请帮帮我。

我只想根据Barcodegroupmap中的latested createddate显示一个条形码项目。

2 个答案:

答案 0 :(得分:1)

我无法实际尝试此查询,因为我没有相关的表和数据,但这应该可以让您入门:

SELECT BarcodeItem, temp.CategoryID, cm.CategoryName, temp.ProductID, pm.ProductName, EffectFrom FROM ( 
  SELECT BarcodeItem, CategoryID, ProductID, CONVERT(date, EffectFrom) as EffectFrom,
    RANK() OVER (PARTITION BY BarcodeItem ORDER BY EffectFrom DESC) dest_rank
    FROM BarcodeGroupMap
  ) temp
  inner join CategoryMaster cm on cm.CategoryID = temp.CategoryID
  inner join ProductMaster pm on pm.ProductID = temp.ProductID
  where temp.dest_rank = 1

答案 1 :(得分:1)

您可以加入表吗?

SELECT bgm.BarcodeItem,
cm.CategoryID,cm.CategoryName,pm.ProductName,pm.ProductID,bgm.EffectFrom,bgm.Groups
from BarcodeGroupMap bgm
INNER JOIN CategoryMaster cm on bgm.categoryID=cm.CategoryID
INNER JOIN ProductMaster pm ON bgm.ProductID=pm.ProductID 
WHERE bgm.CreatedDate = (select top 1 CreatedDate from  BarcodeGroupMap bm2  
WHERE bgm.BarcodeItem = bm2.BarcodeItem ORDER BY CreatedDate  desc) order by bgm.BarcodeItem

如果您不想加入

select bgm.BarcodeItem,
cm.CategoryID,cm.CategoryName,pm.ProductName,pm.ProductID,bgm.EffectFrom,bgm.Groups
from BarcodeGroupMap bgm,CategoryMaster cm,ProductMaster pm where
bgm.ProductID=pm.ProductID  and bgm.categoryID=cm.CategoryID and
where bgm.CreatedDate=  (select top 1 CreatedDate from  BarcodeGroupMap bm2  
WHERE bgm.BarcodeItem = bm2.BarcodeItem ORDER BY CreatedDate  desc) order by bm1.BarcodeItem