Xorthax can now look backward and forward between rows. But sometimes he wants something simpler:
What is the first value in this group?
That's what FIRST_VALUE() does.
FIRST_VALUE() returns the first value in a sequence of rows.
FIRST_VALUE(column) OVER (
PARTITION BY column
ORDER BY column
)
Hereโs why:
PARTITION BY defines the groupORDER BY defines which row is first| CustomerID | OrderDate | Amount |
|---|---|---|
| A | 2024-01-01 | 100 |
| A | 2024-01-05 | 150 |
| B | 2024-01-02 | 200 |
| B | 2024-01-06 | 50 |
SELECT CustomerID, OrderDate, Amount,
FIRST_VALUE(Amount) OVER (
PARTITION BY CustomerID
ORDER BY OrderDate
) AS FirstAmount
FROM Orders;
Result:
| CustomerID | OrderDate | Amount | FirstAmount |
|---|---|---|---|
| A | 2024-01-01 | 100 | 100 |
| A | 2024-01-05 | 150 | 100 |
| B | 2024-01-02 | 200 | 200 |
| B | 2024-01-06 | 50 | 200 |
Each row now shows the first value within its customer group.
PARTITION BY CustomerID creates a group for each customer.
ORDER BY OrderDate defines the sequence within each group.
FIRST_VALUE() looks at the first row in that ordered sequence.
That value is then repeated for every row in the group.
If you change the order, you change what counts as first. And you must have an ORDER BY so SQL knows what is first!
For each order, show the totalamount from the first order based on orderdate.
| Column | Type |
|---|---|
| orderid | bigint |
| customerid | bigint |
| orderdate | timestamp without time zone |
| totalamount | double precision |
| status | text |
| Column |
|---|
| orderid |
| orderdate |
| totalamount |
| first_amount |
FIRST_VALUE() gives you the beginning of a sequence.
Next, you'll learn how to get the value at the end.