Skip to content
Advertisement

SQL – How to query values that are greater than the value appeared on the first day of usage?

I have the following (table).

"customers_dishes"
id - customer id, STRING
date - date of arriving at the restaurant, DATE
bill - total bill, DOUBLE

I am trying to output all of the incidents of customers that their bill was greater than their first date visiting the restaurant bill

id, date, bill
Alen, 2018-03-01, 50
Alen, 2018-03-02, 48
Alen, 2019-03-01, 60
Bob, 2018-03-04, 45
Bob, 2018-03-06, 55
Bob, 2019-03-01, 50

the output should be:

id, date, bill
Alen, 2019-03-01, 60
Bob, 2018-03-06, 55
Bob, 2019-03-01, 50

Tried doing something like that:

SELECT (*) FROM customers_dishes
WHERE date NOT IN (
SELECT date FROM customers_dishes ORDER BY id, date ASC LIMIT 1)
AND id NOT IN(
SELECT id FROM customers_dishes ORDER BY id, date ASC LIMIT 1)

Any suggestions please?

Advertisement

Answer

You can use first_value():

select cd.*
from (select cd.*,
             first_value(bill) over (partition by id order by date) as first_bill
      from customers_dishes cd
     ) cd
where bill > first_bill;

You can also use a correlated subquery:

select cd.*
from customers_dishes cd
where cd.bill > (select cd2.bill
                 from customers_dishes cd2
                 where cd2.id = cd.id
                 order cd2.date
                 fetch first 1 row only
                );
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement