Search code examples
mysqlsql

Brand name whose amount is increasing every year


I have table with three columns year, brand, amount and I want a query that return records of brand whose amount is increasing for every year.

I have pasted below the sample input data and expected output data.

table format:

year_v Brand Amount
2018 P&G 50000
2019 P&G 45000
2020 P&G 60000
2018 IBM 55000
2019 IBM 60000
2020 IBM 70000
2018 EY 80000
2019 EY 40000
2020 EY 36000

Expected output:

year_v Brand Amount
2018 IBM 55000
2019 IBM 60000
2020 IBM 70000

As for IBM, amount is increasing every year.


Solution

  •  SELECT *
     FROM brands
     WHERE brand IN (SELECT brand
                       FROM (SELECT brand, (amount - LAG(amount, 1, 0) OVER (PARTITION BY brand ORDER BY year_v)) diff
                               FROM brands) t
                      GROUP BY brand
                     HAVING MIN(diff) > 0);
    

    lag(): LAG (scalar_expression [,offset] [,default]) OVER ( [ partition_by_clause ] order_by_clause )

    There may be scope for refactoring this query, but I will leave it to the OP to decide.


    Demo