Home  >  Q&A  >  body text

Add highest value as a column using window function

I have a table as follows:

Query to copy data:

DROP TABLE IF EXISTS units_table;
CREATE TEMP TABLE units_table
(
 Brand varchar(100),
 units numeric(38,12)
);


  INSERT INTO units_table (Brand, units)
   VALUES ('A',200),('B',0),('C',300),('D',400),('E',1500),('F',700),('G',800),('H',450);

Specially using window functions, I want to get the highest value in the table. As follows:

But when I use:

select

brand,
units,
FIRST_VALUE(units) OVER () as Highest

from units_table

The first value it gives is 0. If I do this,

select

brand,
units,
FIRST_VALUE(units) OVER (ORDER BY UNITS) as Highest

from units_table

Throw an error. How specifically should Window Function be used to solve this problem? Thank you in advance!

P粉043295337P粉043295337178 days ago412

reply all(2)I'll reply

  • P粉616383625

    P粉6163836252024-04-05 11:32:53

    select brand,units,
     FIRST_VALUE(units) OVER (ORDER BY UNITS DESC) as Highest
    from units_table

    Useful to me

    reply
    0
  • P粉959676410

    P粉9596764102024-04-05 09:38:42

    You needMAX()Window function:

    SELECT brand,
           units,
           MAX(units) OVER () AS Highest
    FROM units_table;

    See Demo.

    reply
    0
  • Cancelreply