我有以下表格:
BarcodeGroupMap:
正如我们在“组”字段中看到的,根据其EffectFrom日期,我有不同的组和barcodeItem。
我只想根据群组对条形码项目进行分组,但对于相同的条形码项目,它应该考虑最近/最大效果从日期开始。
输出我的愿望:
Group BarcodeItem EffectFrom 1 1 2013-11-10 1 11 2013-11-14 1 22 2013-11-10 (max date amount 3 for barcode item 22) 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
但不工作。请帮帮我。
答案 0 :(得分:1)
select groups as [group], barcodeitem, max(EffectFrom) as EffectFrom
from BarcodeGroupMap
group by groups, barcodeitem
order by groups, barcodeitem
答案 1 :(得分: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 演示