Some Interesting and Useful SQL Commands
SQL or in other words Structured Query Language is an essential skill which every developer would like to have in their arsenal. Its a powerful language to interact with SQL Database. Despite its popularity lot of developers struggle to use some basic commands. Here we are going to see some interesting and Useful SQL commands and their use with the help of an example.
Let me state the problem statement first and then we can try to solve the problem using SQL Query.
Problem Statement
We are given a table which describes the Train Departure Timings from different stations as shown in the figure below:
We are asked to return the results of second most recently departed train from each station. So from the example table above the result would contain the following records:
Lets see how we can get the result using SQL.
Solution
- Row Number corresponding to each group.
- Count of Number of records belonging to each station
1 2 3 4 5 6 7 8 | with new_table as (Select * ,row_number() over (partition by Station order by DepartureTime DESC) as rowNum ,count(*) over (partition by Station order by DepartureTime DESC range between unbounded preceding and unbounded following) as Cnt from TrainSchedule) select * from new_table where rowNum = case when Cnt = 1 then 1 else Cnt - 1 end; |
The later select query gives us the final results where we are selecting the records where the row number = Count of records belonging to each group - 1 if the count > 1 else we are selecting the first record itself.
Result
Here we have touched upon few Interesting and useful SQL commands which does the partitioning of the records based on certain column using the partition by construct then ordering each partition by descending order using the order by <Column Name> DESC/ASC. Specifying the range using the range between construct and finally using the conditional case statement in the Select query.
Comments
Post a Comment