2

I have a table which holds hospital admission date, discharge date and the diagnosis:

enter image description here

Now I am trying to get count of readmission within last one year and the history for each encounter (Discharge date + Diagnosis). The outcome should looks something like this:

enter image description here

I am able to get the count but struggling with the history. This is my code:

SELECT
    A.Encounter, A.Patient, A.AdmissionDt, A.DischargeDt, 
    (SELECT COUNT(*) 
     FROM MyTable B 
     WHERE A.Patient = B.Patient 
       AND B.AdmissionDt >= DATEADD(YY, -1, A.DischargeDt) 
       AND B.AdmissionDt < A.DischargeDt) AS Cnt 
FROM
    MyTable A 
ORDER BY
    AdmissionDt DESC

Can I get some help please?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Monte
  • 103
  • 1
  • 1
  • 5
  • Can use STRING_AGG aggregate function to build the concatenated diagnosis history if you are using SQL Server 2017, otherwise will have to use a correlated subquery with `FOR XML` option. – EzLo Dec 27 '18 at 15:15
  • Are you trying to get history for display? If this is a display, you probably don't want to concat a string in SQL. Format the display of multiple records in your output code. – Shawn Dec 27 '18 at 15:23
  • What version of SQL? – Shawn Dec 27 '18 at 15:24
  • And will this be done for just one patient, or will you be looking at multiple patients? – Shawn Dec 27 '18 at 15:25

2 Answers2

3

You can get both of your desired columns from correlated subqueries.

The count column would simply be a COUNT(*) of rows for the same patient before the current row but within the last year.

The History would be a FOR XML concatenation of the same set of rows as the count (before the current row but within the last year).

Tab Alleman
  • 31,483
  • 7
  • 36
  • 52
1

Can you try this query

SELECT A.encounter, 
       A.patient, 
       A.admissiondt, 
       A.dischargedt, 
       (SELECT Count(*) 
        FROM   mytable B 
        WHERE  A.patient = B.patient 
               AND B.admissiondt >= Dateadd(yy, -1, A.dischargedt) 
               AND B.admissiondt < A.dischargedt) AS Cnt, 
        (SELECT  convert (varchar,b.admissiondt) +' - ' + b.diagnosis +'
        '
        FROM   mytable B
        WHERE  A.patient = B.patient 
               AND B.admissiondt >= Dateadd(yy, -1, A.dischargedt) 
               AND B.admissiondt < A.dischargedt  for xml path ('')) as history 
FROM   mytable A 
ORDER  BY admissiondt DESC
Anson Aricatt
  • 391
  • 2
  • 8