1

我有两张桌子:

表 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

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

谢谢!

4

1 回答 1

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

于 2012-04-20T20:01:04.697 回答