Introduction.
Structured Query Language (SQL) is one of the most important tools used by data analysts, data scientists and data engineers to extract, structure, manipulate and analyse data within relational databases. Within a hospital management system, SQL can be used to look at patient data, track admissions, calculate costs of treatments, look at doctor performance and produce reports.
In addition to basic commands like SELECT, INSERT, UPDATE and DELETE, there are many additional tools available to help you perform more complex data analysis. Four very important concepts to understand are window functions, SQL joins, Common Table Expressions (CTEs) and subqueries.
This article will explain what they are, how they work, when to use them and how they can be used to solve real world problems in a hospital setting. Examples using SQL will be given for each concept, including an explanation of the query and what you would expect to see.
Assumptions about the data: As the exact data from the hospital and attached class notes isn't visible within this message, examples have been created using a sample hospital database. This will include tables such as patients, doctors, departments, admissions and payments. The queries use general SQL syntax which should be widely supported, but some features may depend on the database you're using. You can change the table and column names to match those in your class dataset.
1. SQL Window Functions.
1.1 What are SQL window Functions?
The window function allows you to perform calculations on sets of related rows. These functions work slightly differently to standard aggregate functions. Window functions calculate values for each row of data based on the specified set/ window of data.
A hospital administrator may want to know:
What is the ranking of doctors based on how many patients they see?
1.2 Understanding the Over () clause.
The OVER() clause tells SQL which rows a window function should consider when performing its calculation.
Example:
SELECT
admission_id,
patient_id,
admission_cost,
AVG(admission_cost) OVER () AS hospital_average_cost
FROM admissions;
Explanation:
- AVG(admission_cost) calculates the average admission cost.
- OVER() defines the window over which the calculation takes place.
- Because no partition or ordering is specified, the average is calculated across all rows included in the query.
- Each admission remains in the result, and each row displays the same hospital-wide average.
1.3 The Partition By clause.
PARTITION BY divides the result set into separate groups. A window function then performs its calculation independently within each group.
Example: Calculate the average admission cost for each department.
SELECT
admission_id,
department_id,
admission_cost,
AVG(admission_cost) OVER (
PARTITION BY department_id
) AS department_average_cost
FROM admissions;
Explanation: The admissions will be grouped by department_id and each admission will have a column showing the average cost of admissions for their department, but we won't aggregate into one row.
For example: If the average cost of admissions in the Cardiology department is KSh 20,000, each admission in Cardiology will have a column with the value KSh 20,000.
1.4 The Order By clause.
Within OVER(), ORDER BY determines the order in which rows are ranked or processed by the window function.
Example: Rank admissions by cost, from highest to lowest.
SELECT
admission_id,
admission_cost,
ROW_NUMBER() OVER (
ORDER BY admission_cost DESC
) AS cost_position
FROM admissions;
Explanation: The highest priced admission gets value 1, then next highest gets value 2 etc. Even if two admission prices are the same, the ROW_NUMBER() function will still assign unique values. This may lead to an arbitrary ordering of the results unless we have a tiebreaker.
1.5 Window Frames.
The window frame determines which of the rows in the window are included in the calculation for the current row. This is useful when performing running totals, moving averages or rolling calculations.
Common window frames are:
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW will start from the first row in the window up to and including the current row.
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW will take the current row and the previous 2 rows.
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING Will take from the current row up to and including the last row in the window.
Example: Calculate a running total of hospital admissions revenue.
SELECT
admission_id,
admission_date,
admission_cost,
SUM(admission_cost) OVER (
ORDER BY admission_date, admission_id
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS running_revenue
FROM admissions;
Explanation: The SQL will sort the admissions based on the admission date and admission ID. It will then add up the admission fee and give us a running total. The first row will show the cost, the second will show the running total up to that point etc.
If the admission costs are 5000KSh, 8000KSh and 2000KSh respectively, the SQL will return:
5000KSh, 13000KSh, 15000KSh.
The difference between having an ORDER BY clause inside the OVER() function and having it at the end of your SQL is that it will decide the order in which the calculations happen. Whereas having an ORDER BY clause at the end of your SQL will decide how the data will appear.
1.6 Types of SQL window Functions.
Window functions can be divided into ranking functions, navigation functions, value functions, and aggregate window functions
Row_Numbers().
What it does
Gives a unique sequential number to each row in a window starting at 1.
Why it is used
Can be used to see the earliest admission, pick the most recent entry per patient or to eliminate duplicated entries by ranking.
Example in hospital
To give a sequential count of admissions per patient.
SELECT
patient_id,
admission_id,
admission_date,
ROW_NUMBER() OVER (
PARTITION BY patient_id
ORDER BY admission_date DESC, admission_id DESC
) AS admission_number
FROM admissions;
Rank().
What it does
Sorts your data into a specific order and assigns each row a number. If two rows have the same value they will be given the same rank, however there will be gaps between the next ranks.
Why you would use it
It can be useful to find out which of your doctors are performing the best or which department makes the most revenue, whilst allowing for the same ranks.
SELECT
doctor_id,
SUM(admission_cost) AS total_revenue,
RANK() OVER (
ORDER BY SUM(admission_cost) DESC
) AS revenue_rank
FROM admissions
GROUP BY doctor_id;
Dense_Rank().
Purpose: This function ranks your data (like RANK()) without leaving gaps between duplicate values.
Why it's useful: Useful if you want to rank departments or doctors in a hospital that have the same level of performance, consecutively.
SELECT
doctor_id,
SUM(admission_cost) AS total_revenue,
DENSE_RANK() OVER (
ORDER BY SUM(admission_cost) DESC
) AS dense_revenue_rank
FROM admissions
GROUP BY doctor_id;
Ntile().
Function
Split the ordered rows into a certain number of roughly equal buckets.
Usage
Hospitals can split patients into 4 categories based on cost. Doctors can be compared based on the quartile of work they do. Patients can be split into groups based on how long they stay in.
SELECT
patient_id,
admission_cost,
NTILE(4) OVER (
ORDER BY admission_cost
) AS cost_quartile
FROM admissions;
Lag().
What it does: Retrieves a value from a preceding row in the ordered window without requiring a self-join.
Why it is used: It helps compare a patient's current admission cost with their previous admission cost or compare a department's monthly revenue with the previous month.
SELECT
patient_id,
admission_date,
admission_cost,
LAG(admission_cost) OVER (
PARTITION BY patient_id
ORDER BY admission_date, admission_id
) AS previous_admission_cost
FROM admissions;
Lead().
What it does: Retrieves a value from a following row in the ordered window.
Why it is used: It can help examine the next scheduled appointment, the next admission, or a future record in a patient's treatment history.
SELECT
patient_id,
admission_date,
admission_cost,
LEAD(admission_cost) OVER (
PARTITION BY patient_id
ORDER BY admission_date, admission_id
) AS next_admission_cost
FROM admissions;
2. SQL Joins.
2.1 What are SQL joins?
A Join in SQL is used to combine data from two or more tables. In relational databases, data is stored in tables to avoid duplication.
For example a hospital could have a patients table containing information about their patients, a doctors table containing information about their doctors and an admissions table containing information about when they admitted them. Using a join you can write a query to bring together all of this data (patients name, doctors name and admittance date).
Types of Joins.
Inner join.
Function:
Returns only rows which meet the joining criteria of both tables.
Use:
If you wish to produce a report which only contains admissions which have an existing patient record this function can be used.
Example:
SELECT
p.patient_id,
p.patient_name,
a.admission_id,
a.admission_cost
FROM patients AS p
INNER JOIN admissions AS a
ON p.patient_id = a.patient_id;
Left join.
Function: Returns all the rows from the left table, and any matching rows from the right table. If there are no matching rows in the right table then all columns in the right table will be NULL.
Use: Can be useful in situations where Hospital Management want to see a list of all the patients that are registered with them even if they have never been admitted.
Example:
SELECT
p.patient_id,
p.patient_name,
a.admission_id,
a.admission_cost
FROM patients AS p
LEFT JOIN admissions AS a
ON p.patient_id = a.patient_id;
Right join.
It will return all records from the right table and any matched records from the left table. If there is no match then the columns from the left table will show as NULL.
This can be useful if we want to keep all admission records in the hospital.
Example:
SELECT
p.patient_id,
p.patient_name,
a.admission_id,
a.admission_cost
FROM patients AS p
RIGHT JOIN admissions AS a
ON p.patient_id = a.patient_id;
Full outer join.
What it does: Returns matching rows and any unmatched rows from both tables. Any missing rows will show as NULL.
Why it can be used: To help match patients to admissions, orphan admissions and patients with no admissions.
Example:
SELECT
p.patient_id,
p.patient_name,
a.admission_id,
a.admission_cost
FROM patients AS p
FULL OUTER JOIN admissions AS a
ON p.patient_id = a.patient_id;
Cross Join.
What it does: This function creates a Cartesian product of two tables. Basically it matches every row of the first table to every row in the second table.
Why you would want to do this: Can be useful to create combinations, for example all departments in a hospital with each month they reported.
Example:
SELECT
d.department_name,
m.month_name
FROM departments AS d
CROSS JOIN (
SELECT 'January' AS month_name
UNION ALL
SELECT 'February'
) AS m;
Self Join.
What it does:
It joins a table with itself but with different aliases.
When would I use it:
You can use this when you have a hierarchical relationship between pieces of data, for example joining hospital staff to their manager.
Example:
SELECT
e.employee_name AS employee,
m.employee_name AS manager
FROM employees AS e
LEFT JOIN employees AS m
ON e.manager_id = m.employee_id;
3. Common Table Expressions (CTEs).
What is a CTE?
A Common Table Expression (CTE) is a temporary result set that can be referenced by name in a statement using the WITH clause.
They help break down complicated SQL queries into simpler manageable parts as they let us create some intermediate results to be referred to by their name.
In a hospital setting CTEs can be used to aggregate admission information, find out how much money departments make, see which cases are most expensive and produce reports in a hierarchy.
3.1 Basic CTE.
Example:
WITH patient_costs AS (
SELECT
patient_id,
SUM(admission_cost) AS total_cost
FROM admissions
GROUP BY patient_id
)
SELECT
patient_id,
total_cost
FROM patient_costs
WHERE total_cost > 20000;
Expalantion:
- The CTE groups the data by patient into a table called patient_costs
- Calculates the total admission cost for each patient using SUM(admission_cost).
- Selects only those patients with an admission cost > KSh 20,000 We would expect this to return a list of patient IDs and how much they spent on admission (only those that spent more than the threshold) This CTE can make the query easier to read.
Multiple CTE.
A query can define multiple CTEs, allowing each step to build on a previous one.
Example:
WITH patient_costs AS (
SELECT
patient_id,
SUM(admission_cost) AS total_cost
FROM admissions
GROUP BY patient_id
),
ranked_patients AS (
SELECT
patient_id,
total_cost,
DENSE_RANK() OVER (
ORDER BY total_cost DESC
) AS cost_rank
FROM patient_costs
)
SELECT
patient_id,
total_cost,
cost_rank
FROM ranked_patients
WHERE cost_rank <= 5
ORDER BY cost_rank, patient_id;
Explanation:
patient_costs will calculate the total cost for each patient.
ranked_patients will assign a dense rank to the patients based on their total cost.
The final query will return the top 5 ranked patients.
We expect to see a list of the most expensive patients. As it uses dense rankings there may be more than 5 rows returned as some patients may tie in the top 5 unique rankings.
This can be useful to provide to management. Each part has a clear purpose.
Recursive CTEs.
A recursive CTE uses recursion to query hierarchical or sequential data. This is often used to navigate organisational structures or category trees.
A recursive CTE will usually consist of:
An anchor member that provides initial data.
A recursive member which queries the previous result to get the next level of data.
A terminating condition where no further data is returned.
4. SQL Subqueries.
What is a subquery?
This is a query within another query in SQL. This can help you to use the results of one query as a value, list of values or a table for another query.
Subqueries can help you compare values with averages, filter out information using a relevant set of data or perform calculations on your data to give you your final results. This can be useful in hospital reports.
4.1 Scalar subqueries.
What they do: Return a single value (usually 1 row and 1 column)
Why they are used: To compare each record against a single calculated value (such as the average cost of admission in the whole hospital).
Example:
SELECT
admission_id,
patient_id,
admission_cost
FROM admissions
WHERE admission_cost > (
SELECT AVG(admission_cost)
FROM admissions
);
The inner query finds the average cost of admissions. The outer query then shows all admissions where the cost is higher than the average.
Output:
Admissions that have an admission cost higher than the average of all admissions.
As these queries only return a single row of data, if they return more than one row in a situation where only 1 should be returned, many SQL systems will throw an error. If they return zero rows, they will usually return a NULL value.
4.2 Non-correlated subqueries.
They are executed outside of the current row context of the outer query because their query does not refer to any columns
Why use them? To pre-calculate a value such as a threshold or find a list of relevant IDs before applying filters in the outer query.
4.3 Correlated subqueries.
What they do: You will have a reference to a column from the outside query. This means the outcome of the subquery will change based on the current row from the outer query.
Why they are useful: This can be useful when you want to compare a record against other records within the group. For instance looking at admissions where the cost is higher than the average for that department.
4.4 Nested subqueries.
This allows you to nest subqueries, so you can have multiple levels of filtering/calculation.
They are useful when you need to find a group and compare data within this group or to it.
Find patients with an admission in the department with the highest average admission cost.
4.5 Subqueries using IN.
Purpose: To test if a value exists in a list of values returned from a subquery.
Use: This can be useful if you want to find patients that are part of a group e.g. Patients admitted to a certain department.
Example:
SELECT
patient_id,
patient_name
FROM patients
WHERE patient_id IN (
SELECT patient_id
FROM admissions
WHERE admission_cost > 20000
);
4.6 Subqueries using EXISTS.
Functionality:
Checks that the sub-query returns at least one row.
Usage:
Useful for checking there are patients with at least one admission or departments with at least one related doctor.
Example:
SELECT
p.patient_id,
p.patient_name
FROM patients AS p
WHERE EXISTS (
SELECT 1
FROM admissions AS a
WHERE a.patient_id = p.patient_id
);
Subquery using ANY.
What it means: Compares a value to one or more values in a subquery. At least one of the comparison conditions must evaluate to TRUE.
Why you would use it: You could use this to find admissions that had higher costs than at least one department's average.
Subquery using ALL.
What it does: Compares a value with every value returned by a subquery.
Why it is used: It can identify admissions whose costs exceed the averages of all departments.
COnclusion.
SQL window functions, joins, CTEs and subqueries are vital to analyse relational data. They all have their own uses but can be combined to perform complex analysis.
Window functions can be used to rank, total up, average and compare data without losing any rows of data.
Joins allow you to join together related data from multiple tables. This helps you find matching and non-matching data.
CTEs help break down complex queries into digestible parts. They can also be used for recursive analysis of hierarchical data.
Subqueries allow you to use the output of one query within another. Helping filter, compare and calculate.
These concepts can be used in a Hospital setting to answer questions such as how many patients were admitted, how much each department costs, how much was spent on treatments and more. As a data scientist/data engineer it is useful to understand these concepts as you need to make sure you are pulling back the correct information, understanding the relationships between data and performing the correct calculations to get reliable analysis.
The most important thing is not knowing the SQL syntax but understanding what you are trying to do, what type of query to write and correctly interpreting your results.
Top comments (0)