mardi 31 octobre 2017

Create distinct result set with two datasets

In SAS, I have the following two datasets:

Dataset #1: Data on people's meal preferences

   ID |  Meal   | Meal_rank
    1   Lobster       1
    1   Cake          2
    1   Hot Dog       3
    1   Salad         4
    1   Fries         5
    2   Burger        1
    2   Hot Dog       2
    2   Pizza         3
    2   Fries         4
    3   Hot Dog       1
    3   Salad         2
    3   Soup          3
    4   Lobster       1
    4   Hot Dog       2
    4   Burger        3

Dataset #2: Data on meal availability

  Meal   | Units_available
  Hot Dog     2
  Burger      1
  Pizza       2

In SAS, I'd like to find a way to derive a result dataset that looks as follows (without changing anything in Dataset #1 or #2):

   ID |  Assigned_Meal
    1   Hot Dog
    2   Burger
    3   Hot Dog
    4   Meal cannot be assigned (out of stock/unavailable)

The results are driven by a process that iterates through the meals of each person (identified by their 'ID' values) until either:

  1. A meal is found where there are enough units available.
  2. All meals have been checked against the availability data.

Notably:

  1. There are cases where the person lists a meal that isn't available.

The dataset I'm working with is much larger than in this example (thousands of rows).

Here is SAS code for creating the two sample datasets:

    proc sql;
       create table work.ppl_meal_pref
           (ID char(4),
            Meal char(20),
            Meal_rank num);

    insert into work.ppl_meal_pref
        values('1','Lobster',1)
        values('1','Cake',2)
        values('1','Hot Dog',3)
        values('1','Salad',4)
        values('1','Fries',5)
        values('2','Burger',1)
        values('2','Hot Dog',2)
        values('2','Pizza',3)
        values('2','Fries',4)
        values('3','Hot Dog',1)
        values('3','Salad',2)
        values('3','Soup',3)
        values('4','Lobster',1)
        values('4','Hot Dog',2)
        values('4','Burger',3)
        ;
    quit;
    run;

    proc sql;
       create table work.lunch_menu
           (FoodName char(14),
            Units_available num);

    insert into work.lunch_menu
        values('Hot Dog',2)
        values('Burger',1)
        values('Pizza',1)
        ;
    quit;
    run;

I've tried to implement loops to perform this task, but to no avail.

Aucun commentaire:

Enregistrer un commentaire