Оптимальное решение вопроса собеседования

Recently in a job interview, I was given the following problem.

Say I have the following table

widget_Name        |     widget_Costs      | In_Stock
---------------------------------------------------------
a                   |         15.00          |    1
b                   |         30.00          |    1
c                   |         20.00          |    1
d                   |         25.00          |    1

where widget_name is holds the name of the widget, widget_costs is the price of a widget, and in stock is a constant of 1.

Now for my business insurance I have a certain deductible. I am looking to find a sql statement that will tell me every widget and it's price exceeds the deductible. So if my dedudctible is $50.00 the above would just return

widget_Name        |     widget_Costs      | In_Stock
---------------------------------------------------------
a                   |         15.00          |    1
d                   |         25.00          |    1

Since widgets b and c where used to meet the deductible

The closest I could get is the following

SELECT 
    *
FROM (
     SELECT 
          widget_name, 
          widget_price
     FROM interview.tbl_widgets
     minus
     SELECT widget_name,widget_price
     FROM (
          SELECT 
               widget_name,
               widget_price, 
               50 - sum(widget_price) over (ORDER BY widget_price  ROWS between unbounded preceding and current row) as running_total
          FROM interview.tbl_widgets 
     ) 
     where  running_total >= 0
)
;

Which gives me

widget_Name        |     widget_Costs      | In_Stock
---------------------------------------------------------
c                   |         20.00          |    1
d                   |         25.00          |    1

because it uses a and b to meet the majority of the deductible

I was hoping someone might be able to show me the correct answer

EDIT: I understood the interview question to be asking this. Given a table of widgets and their prices and given a dollar amount, substract as many of the widgets you can up to the dollar amount and return those widgets and their prices that remain

5
задан Scott 11 April 2011 в 18:14
поделиться