SQL LAG,LEAD,Power.SQRT Functions
With the LEAD()
function, you can access data from a subsequent row in the same query, without using the GROUP BY
statement. This way, you can easily compare values from an ordered list.
This is the syntax: LEAD(numeric_expression) OVER ([PARTITION BY column] ORDER BY column)
SELECT
first_name,
last_name,
total_votes AS votes,
-- Select the number of votes of the next voter
LEAD(total_votes) OVER (ORDER BY total_votes) AS votes_next_voter,
-- Calculate the difference between the number of votes
LEAD(total_votes) OVER (ORDER BY total_votes) - total_votes AS votes_diff
FROM voters
WHERE country = 'France'
ORDER BY total_votes;
SELECT
broad_bean_origin AS bean_origin,
rating,
cocoa_percent,
-- Retrieve the cocoa % of the bar with the previous rating
LAG(cocoa_percent)
OVER(PARTITION BY broad_bean_origin ORDER BY rating) AS percent_lower_rating
FROM ratings
WHERE company = 'Fruition'
ORDER BY broad_bean_origin, rating ASC;
First Value and Last Value Function
Getting the first and last value
The analytical functions that return the first or last value from an ordered list prove to be very helpful in queries. In this exercise, you will get familiar with them. The syntax is:
FIRST_VALUE(numeric_expression) OVER ([PARTITION BY column] ORDER BY column ROW_or_RANGE frame)
LAST_VALUE(numeric_expression) OVER ([PARTITION BY column] ORDER BY column ROW_or_RANGE frame)
Sometimes in your database development, you may need to round the results of a calculation. There are three functions you can use for this:
CEILING(expression)
: rounds-up to the nearest integer valueFLOOR(expression)
: rounds-down to the nearest integer valueROUND(expression, length)
: rounds the expression to the specified length.
The exponential functions are useful when you need to perform calculations in the database. For databases storing real estate information, for example, you may need to calculate areas. In this case, these functions may come in handy:
POWER(number, power)
: raises the number to the specified powerSQUARE(number)
: raises the number to the power of 2
Or, if you need to calculate the distance between two cities, whose coordinates are known, you could use this function:
SQRT(number)
: calculates the square root of a positive number.
Comments
Post a Comment