groupby / merge到最新记录?

时间:2012-04-20 19:12:09

标签: sql sql-server tsql

我有两张桌子:

表1:Food_I_Have_In_Fridge:

Food  | Category
---------------
Apple | Fruit
Beef  | Meat
Tomato| Veggie
Pork  | Meat
Bacon | Meat
Orange| Fruit
Carrot| Veggie

表2:Food_I_ate:

Date | Food
------------
Mon  | Apple
Mon  | Beef
Tues | Pork
Thurs| Orange
Sat  | Tomato

我想生成一份我按食品类别分类的最新食品清单。输出如下:

Categ| Food
-----------
Meat | Pork
Fruit| Orange
Veggi| Tomato

我无法分组和合并行,有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

假设您确实 使用工作日的名称作为日期列,这里有一个解决方案,它将工作日转换为工作日索引,并按类别查找最新的食物:

;with FW as (
    select w.ix, f.category, a.food, a.date
    from
        [Food_I_ate] a
    inner join
        [Food_I_Have_In_Fridge] f on a.Food = f.Food
    inner join
    (
        select 0 as ix, 'Sun' as weekdayname union
        select 1, 'Mon' union
        select 2, 'Tues' union
        select 3, 'Wed' union
        select 4, 'Thurs' union
        select 5, 'Fri' union
        select 6, 'Sat'
     ) w on w.weekdayname = a.[Date]
)
select
    FW2.category,
    FW2.Food,
    FW2.Date
from
    (select FW.category, max(fw.ix) as maxix
     from FW group by FW.category) FW
inner join
    FW FW2 on FW2.ix = FW.maxix and FW2.category = FW.category

示例输出:

CATEGORY    FOOD    DATE
Veggie      Tomato  Sat
Meat        Pork    Tues
Fruit       Orange  Thurs

演示:http://www.sqlfiddle.com/#!3/4b92f/21