I've been diving deeper into SQL and discovered something new and interesting to me: the difference between RANK() and DENSE_RANK() window functions. I was only aware of RANK(), but skipping ranking after ties bothered me. Here's a concise example of employees and their revenue contributions to the company: | employee_id | employee_name | revenue | | 1 | Alice | 5000 | | 2 | Bob | 7000 | | 3 | Charlie | 7000 | | 4 | David | 6000 | | 5 | Eva | 5000 | ------------------------------------------------------ Consider this query: SELECT employee_id, employee_name, revenue, RANK() OVER (ORDER BY revenue DESC) AS rank, DENSE_RANK() OVER (ORDER BY revenue DESC) AS dense_rank FROM employees; It provides us the result set of: | id | name | revenue | rank | dense_rank | 2 | Bob | 7000 | 1 | 1 | 3 | Charlie | 7000 | 1 | 1 | 4 | David | 6000 | 3 | 2 | 1 | Alice | 5000 | 4 | 3 | 5 | Eva | 5000 | 4 | 3 Do you see the difference? In this example, RANK() skips ranks after ties, whereas DENSE_RANK() does not. Understanding these differences can be crucial.
Yaroslav Pelykh’s Post
More Relevant Posts
-
🌟 𝐃𝐚𝐲 𝟗 of 𝐒𝐐𝐋 𝐉𝐨𝐮𝐫𝐧𝐞𝐲: 𝐄𝐱𝐩𝐥𝐨𝐫𝐢𝐧𝐠 𝐃𝐚𝐭𝐞 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬! 🌟 Today, I focused on the essential date functions in SQL, which are vital for manipulating and analyzing date and time data effectively. 📅✨ 🔍 𝐖𝐡𝐚𝐭 𝐈 𝐂𝐨𝐯𝐞𝐫𝐞𝐝: In my latest presentation, I delved into various date functions, such as GETDATE(), DATEADD(), DATEDIFF(), and more. Each function has unique applications that enhance data analysis capabilities. 💡 𝐖𝐡𝐲 𝐈𝐭 𝐌𝐚𝐭𝐭𝐞𝐫𝐬: Mastering these date functions enables us to handle time-based data accurately, ensuring reliable analysis and reporting. These tools are crucial for tasks like calculating durations, summarizing monthly trends, and tracking user activity. 🚀 I’m excited to continue my SQL journey and explore even more functionalities! If you have insights or tips about using date functions effectively, feel free to share! Also, I came across a fantastic YouTube video by Ankit Bansal that explains all these date functions in detail which has been incredibly helpful!. Do check it out here: https://lnkd.in/gGJ8qjTA Check out my PPT for detailed explanations of each function! #𝐒𝐐𝐋𝐉𝐨𝐮𝐫𝐧𝐞𝐲 #𝐃𝐚𝐭𝐚𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬 #𝐒𝐐𝐋 #𝐃𝐚𝐭𝐞𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 #𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐉𝐨𝐮𝐫𝐧𝐞𝐲 #𝐂𝐨𝐝𝐞𝐛𝐚𝐬𝐢𝐜𝐬 #𝐍𝐚𝐦𝐚𝐬𝐭𝐞𝐒𝐐𝐋 #𝐃𝐚𝐭𝐚𝐒𝐞𝐧𝐬𝐞
To view or add a comment, sign in
-
Hello busy people, Let's talk about a hidden gem in SQL: the QUALIFY keyword! 👀 What is QUALIFY? QUALIFY filters results of window functions directly, making your queries cleaner and more readable. Example: Imagine you need to find the most recent purchase for each customer. Here’s how QUALIFY can help: SELECT customer_id, purchase_date, purchase_amount, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY purchase_date DESC) as purchase_rank FROM purchases QUALIFY purchase_rank = 1; Why Use QUALIFY? - Simplifies queries by keeping window function logic and filtering together - Reduces the need for complex subqueries See you in the next one! #SQL #DataAnalysis #BigData #DataScience #SQLTips #DataAnalytics #QUALIFY
To view or add a comment, sign in
-
⏳ 𝗦𝗤𝗟 𝗞𝗲𝘆𝘄𝗼𝗿𝗱 𝗦𝗽𝗼𝘁𝗹𝗶𝗴𝗵𝘁: 𝗨𝗻𝗹𝗼𝗰𝗸 𝘁𝗵𝗲 𝗣𝗼𝘄𝗲𝗿 𝗼𝗳 𝗘𝗫𝗧𝗥𝗔𝗖𝗧 𝗶𝗻 𝗦𝗤𝗟! ⏳ 𝗗𝗮𝘆 𝟯𝟮 𝗼𝗳 #𝗦𝗤𝗟𝗗𝗮𝗶𝗹𝘆𝗗𝗼𝘀𝗲 : Ever felt overwhelmed working with 𝗱𝗮𝘁𝗲𝘀 𝗮𝗻𝗱 𝘁𝗶𝗺𝗲𝘀 in your database? Say hello to 𝗘𝗫𝗧𝗥𝗔𝗖𝗧 — a powerful SQL keyword that lets you dissect date and time values with surgical precision. Whether it’s isolating the year from a timestamp or pulling out just the hour from a log entry, 𝗘𝗫𝗧𝗥𝗔𝗖𝗧 makes it effortless. 𝗪𝗮𝗻𝘁 𝘁𝗼 𝗹𝗲𝗮𝗿𝗻 𝗺𝗼𝗿𝗲? Check out this slide deck, where I dive into the nuances of EXTRACT, its syntax, and practical applications for real-world scenarios. How do you work with dates in your projects? Let’s share tips and insights below! 👇 #SQL #DataAnalytics #DataEngineering #SQLTips #SQLDailyDose #DatabaseManagement #TimeSeriesAnalysis #DateHandling
To view or add a comment, sign in
-
Dear Excel Santa 🎅, Here's what I would love to see: - in-cell usable lambda functions (see image) - support for typed arrays of functions i.e. so we can type {SUM, MIN, MAX} instead of HSTACK(SUM, MIN, MAX) - support for function equality operations i.e. so that LAMBDA(x, SUM(x)) = SUM returns TRUE - a SIGNATURE() function that returns a rich object describing a function signature, so we can ensure that a function expects the same number of arguments I'm going to provide it, that also supports equality operations. SILLYEXAMPLE = LAMBDA(x, y, fn, IF( SIGNATURE(fn) = SIGNATURE(LAMBDA(x, y, "anything"), fn(x, y), "Signature of provided function is incorrect" ) ); - support for partial application. Suppose I have a function like this: TRIVIALEXAMPLE = LAMBDA(multiplier, array, array * multiplier); Then partial application would allow this: =BYROW(AnArray, TRIVIALEXAMPLE(3)) So that we provide the first n arguments, and missing arguments are passed by the calling function. In this case, missing argument is "array", and it's passed by BYROW as the array of values for a row. Owen --- ❓ What's in your letter to Excel Santa for 2024? #data #analytics #excel #lambda
To view or add a comment, sign in
-
-
Click here to see the complete textual solution on Google Docs- https://lnkd.in/dxxBR8sf 🎄 Merry Christmas, everyone! 🎄 Today marks the beginning of my SQL journey, where I'll be solving a series of SQL questions and sharing the answers with you all. I’m excited to start Day 1 and eager to dive deeper into data analysis using SQL! Let's start with today's solutions. Solutions: 1. SELECT week, SUM(quantity) AS total_quantity FROM orders_analysis WHERE week >= '2023-01-01' AND week <= '2023-03-31' GROUP BY week ORDER BY week; 2. SELECT user_id, ROUND(SUM(listen_duration) / 60) AS total_listen_duration, COUNT(DISTINCT song_id) AS unique_song_count FROM listening_habits GROUP BY user_id; 3. SELECT u.user_id, COALESCE(COUNT(DISTINCT a.activity_type), 0) AS unique_activity_count FROM user_profiles u LEFT JOIN activity_log a ON u.user_id = a.user_id GROUP BY u.user_id ORDER BY u.user_id; 4. SELECT guest_id, RANK() OVER (ORDER BY age DESC) AS guest_rank FROM airbnb_guests ORDER BY age DESC; 5. SELECT hour, AVG(travel_distance) AS average_traveled_distance FROM user_profiles GROUP BY hour ORDER BY hour; Thank you all for your support as I continue to grow my SQL skills and explore the world of data analysis. Stay tuned for more questions and solutions as I move forward on this journey. #SQL #DataAnalysis #LearningJourney #MerryChristmas #SQLSolutions #DataAnalytics Ankit Bansal, Rishabh Mishra Feel free to replace the your-google-doc-link with your actual Google Docs link. Let me know if you'd like any changes!
To view or add a comment, sign in
-
🌟Today, I spent some time exploring some advanced SQL concepts: ROW_NUMBER(), RANK(), DENSE_RANK(), and PARTITION BY(). I’m diving deep into how these functions work and their differences. Here’s a quick summary of what I’ve learned so far: ✅ ROW_NUMBER(): Assigns a unique number to each row, starting from 1 within each group. ✅RANK(): Gives ranks but skips numbers when rows have the same value. ✅DENSE_RANK(): Similar to RANK but doesn’t skip numbers. ✅PARTITION BY(): Groups data into partitions, so functions like ROW_NUMBER or RANK can operate independently within each group. I’ve attached a file where I’ve documented these concepts in more detail. If you have any constructive feedback or tips would love to hear that! 😊 #AdvancedSQL #DataAnalytics #SQL #LearningSQL #SQLConcepts #DataAnalytics #SQLForDataAnalysis
To view or add a comment, sign in
-
Day 20/30 of My SQL Challenge: Intermediate SQL with Window Functions & Ranking 📊🏆 Today’s challenge was all about diving deeper into window functions and ranking—key techniques for performing complex calculations across data sets without altering the results of a query. 💻 Today's Tasks: 1. Ranking Products by Total Sales – I used the RANK() window function to rank products based on total sales. This is a great way to quickly see which products are performing best. 2. Calculating a Running Total of Orders – Next, I applied the SUM() window function to calculate the running total of orders across a period, providing insights into sales trends over time. 💬 Window functions are incredibly powerful for advanced analytics—whether you’re ranking data or calculating running totals, they let you perform complex calculations while maintaining visibility into the entire dataset. #SQL #DataAnalytics #WindowFunctions #IntermediateSQL #Ranking #RunningTotal #SQLChallenge #LearningJourney #TechJourney #DataScience #AdvancedQueries
To view or add a comment, sign in
-
-
🚀 Mastering SQL: The Power of Window Functions and CTEs! Recently, I’ve been diving deep into SQL and discovered how window functions and Common Table Expressions (CTEs) can make querying data so much more efficient and insightful. Here’s a quick example of their combined power: Scenario: Imagine you’re analyzing customer bookings and want to identify the top 3 cities per country based on booking volume. Sounds tricky? Let SQL handle it! WITH BookingRank AS ( SELECT country, city, COUNT(*) AS booking_count, RANK() OVER (PARTITION BY country ORDER BY COUNT(*) DESC) AS rank FROM bookings GROUP BY country, city ) SELECT * FROM BookingRank WHERE rank <= 3; Breakdown: 🔹 CTE (BookingRank): Simplifies the query by organizing intermediate results. 🔹 Window Function (RANK): Dynamically ranks cities within each country based on booking counts. 🔹 Output: Only the top 3 cities per country. This approach keeps your query clean and helps you focus on the insights without over-complicating the logic. If you’re exploring SQL or working on analytics, understanding these tools can save you hours and unlock actionable insights. 💡 Pro Tip: Practice is key. Start applying these in your daily analysis tasks to get comfortable. What’s your go-to SQL trick for solving complex queries? Let’s share and learn together! #DataAnalytics #SQL #Learning #DataInsights
To view or add a comment, sign in
-
𝑼𝒏𝒍𝒐𝒄𝒌𝒊𝒏𝒈 𝒕𝒉𝒆 𝑷𝒐𝒘𝒆𝒓 𝒐𝒇 𝑺𝑸𝑳: 𝑴𝒂𝒔𝒕𝒆𝒓𝒊𝒏𝒈 𝑾𝒊𝒏𝒅𝒐𝒘 𝑭𝒖𝒏𝒄𝒕𝒊𝒐𝒏𝒔 SQL is a cornerstone for data analysis, and mastering window functions takes your skills to the next level! These powerful tools let you analyze data across rows without collapsing results, enabling insights that aggregate functions alone cannot provide. In my recent exploration, I’ve delved into: 🔹 The difference between ROW_NUMBER, RANK, and DENSE_RANK, and their applications. 🔹 Using PARTITION BY and ORDER BY to customize results across partitions. 🔹 Practical use cases like calculating running totals, moving averages, and year-over-year growth. 🔹 Identifying duplicates with ROW_NUMBER(). 🔹 Optimization tips for large datasets to ensure efficient queries. Whether you're ranking employees by salary, tracking trends in sales, or segmenting data for advanced insights, window functions are invaluable. Want to learn more about how these functions can transform your SQL queries? Let’s connect and share knowledge! #SQL #WindowFunctions #DataAnalytics #DataEngineering #ContinuousLearning
To view or add a comment, sign in