I was helping with this question Correlated Subquery in SQL
Using this QUERY I was able to achive this result
- MRN1: Is the patient
- Accession: Are exam on that patient.
- DateA: The date of exam
- DateB: The date of previous exam
- num_days: Difference of day between exams
.
| MRN1 | rn | Accession1 | DateA | DateB | num_days |
|--------|----|------------|------------------|------------------|----------|
| 001734 | 1 | 33104 | 12/21/2013 06:52 | (null) | (null) |
| 001734 | 2 | 33374 | 01/21/2014 08:19 | 12/21/2013 06:52 | 31 |
| 001734 | 3 | 33399 | 2/19/2014 11:48 | 01/21/2014 08:19 | 29 |
| 001734 | 4 | 34453 | 03/14/2014 09:14 | 2/19/2014 11:48 | 23 |
| 35681 | 1 | 28153 | 09/14/2012 05:00 | (null) | (null) |
| 35681 | 2 | 29007 | 11/16/2012 08:23 | 09/14/2012 05:00 | 63 |
| 80592 | 1 | 27122 | 06/26/2013 10:20 | (null) | (null) |
| 80592 | 2 | 27248 | 08/01/2013 06:23 | 06/26/2013 10:20 | 36 |
But I'm having problem to achive the final result OP want.
I know perform the dynamic pivot when is a basic format
ID fieldName fieldValue
But dont know how handle this table.
My guess is I have to prepare the table first before perform the dynamic pivot.
This is the desire output
| MRN1 | Accession1 | ReadDate1 | Accession2 | ReadDate2 | num_days2 | Accession3 | ReadDate3 | num_days3 | Accession4 | ReadDate4 | num_days4 |
|-------|------------|-----------------------------|------------|----------------------------|-----------|------------|-----------------|-----------|------------|------------------|-----------|
| 1734 | 33104 | December, 21 2013 06:52:00 | 33374 | January, 21 2014 08:19:00 | 31 | 33399 | 2/19/2014 11:48 | 29 | 34453 | 03/14/2014 09:14 | 23 |
| 35681 | 28153 | September, 14 2012 05:00:00 | 29007 | November, 16 2012 08:23:00 | 63 | (null) | (null) | (null) | (null) | (null) | (null) |
| 80592 | 27122 | June, 26 2013 10:20:00 | 27248 | August, 01 2013 06:23:00 | 36 | (null) | (null) | (null) | (null) | (null) | (null) |