I have table:
t_patients (id is auto_increment)
id | patient_id | created_at |
---|---|---|
1 | 100 | 2023-01-10 |
2 | 200 | 2023-01-11 |
3 | 100 | 2023-01-15 |
the result need like this:
patient_id | 1st come | 2nd come | 3rd come |
---|---|---|---|
100 | 2023-01-10 | 2023-01-15 | x |
200 | 2023-01-11 | x | x |
I have googling for this but still didn’t find the exact output as needed. What query the SQL should be?
2
Answers
You can achieve this using COALESCE function in mysql and conditional aggregation.
Here is a demo using DBFIDDLE.
The following query shall give you the expected output :
Output :
I wrote a query without using window function (as MySQL 5.7 and below do not support it). To make things more exciting, let’s add a few rows:
After that, let’s write the query which lines up each patient_id based on each patient’s create_at value. A row_id is given for each of a patient’s create_at value , which starts from 1. Note, the row_id value shall be reset to 1 whenever patient_id changes, so every patient_id can have its row_id start from 1.
The above query is then used as a derived table (aliased as
tb
) for our main query, which does the table pivoting job. Note: Instead of using thecoalesce
function, here I decided to usemin()
function . As numbers serving as strings come before letters in ascii, somin()
will pick up the create_at over letterx
when a create_at value exists .