Skip to content

Tag: sql-server

Query for Exam Score calculation

Problem Statement: I have an EXAM table which has following fields and sample data I want to write a SQL query to output the following fields My SQL Query: Can I achieve my result by writing a better SQL query? Answer You could indeed join the table with several aggregate subqueries that compute the relevant …

Performance improvement Outer Apply

I have a query which runs slower. Order By inside the Outer Apply is very costly, is there any better way to write this query ? Answer From what I can tell in the code, you seem to be implementing a variation of lag(ignore nulls). Here is a better way: Also note that in many databases the “v” in v…

Writing a Single Query w/ Multiple CTE Subqueries SQL/R

I have some data I would like to pull from a database, I’m using RStudio for my query. What I intend to do is write: The first CTE statement to pull all my necessary information. The second CTE statement will add two new columns for two row numbers, which are partitioned by different groups. Two additio…

Flag the date when they return

Story: For each id , they have a join date to a subscription and when they get rebilled monthly, they have a returning date. The first part of the exercise was to flag consecutive months of returned dates from the join date. Here’s an example: Objective: What I would like to add is to flag those who ret…