0

我有下表:

条码组图:

在此处输入图像描述

正如我们在 Groups 字段中看到的那样,根据其 EffectFrom 日期,我有不同的组和 barcodeItem 与之关联。

我只是想根据组对条码项目进行分组,但对于相同的条码项目,它应该考虑最近/最大效果日期。

我想要的输出:

Group BarcodeItem EffectFrom
1 1 2013-11-10
1 11 2013-11-14
1 22 2013-11-10(条形码项目 22 的最大日期数量 3)
1 222 2013-11-14
1 333 2013-11-14
1 3331 2013-11-14

我做了以下查询:

select * from BarcodeGroupMap bm ,

 ( 
  select groups,barcodeitem,bcgmid ,MAX(EffectFrom) as dates,CreatedDate as cdate from BarcodeGroupMap 
  group by groups ,barcodeitem,bcgmid,CreatedDate  having Groups=1 

 ) T 
 where t.Groups =bm.Groups and t.BarcodeItem = bm.BarcodeItem and  T.Groups =  1 and t.dates =bm.EffectFrom  Order by t.BarcodeItem , t.Groups

但不工作。请帮我。

4

2 回答 2

1
select groups as [group], barcodeitem, max(EffectFrom) as EffectFrom
from BarcodeGroupMap 
group by groups, barcodeitem
order by groups, barcodeitem
于 2013-11-15T05:15:12.810 回答
1

更新

SELECT * 
  FROM
(
    SELECT m.*, ROW_NUMBER() OVER (PARTITION BY groups, barcodeitem 
                                   ORDER BY effectfrom DESC, createddate DESC) rnum
      FROM BarcodeGroupMap m
     WHERE groups = 1
) t
 WHERE rnum = 1
 ORDER BY groups, barcode item

这是SQLFiddle演示

于 2013-11-15T05:16:30.550 回答