The LAG() function is valuable when you need to compare or calculate values from the previous row, especially for understanding trends, changes, or patterns within ordered data. In this output, the “previous_day_revenue” column contains the revenue from the sale that occurred on the day immediately preceding each current sale. The result might look like this: sale_date | revenue | previous_day_revenue -+-+- | 100 | NULL | 150 | 100 | 90 | 150 | 200 | 90 In this example, the LAG() function retrieves the revenue from the previous day’s sale for each row based on the order of sale dates. Suppose you have a table named “daily_sales” with columns “sale_date” and “revenue”, and you want to calculate the difference in revenue between the current day’s sales and the previous day’s sales: SELECT sale_date, revenue, LAG(revenue, 1) OVER (ORDER BY sale_date) AS previous_day_revenue FROM daily_sales Here’s a simple example of how to use the LAG() function in PostgreSQL:
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |