سؤال

I hear that I need an array. Not sure what that is and how it applies to my data. Any help is greatly appreciated!

I have data returning in my query that looks like this

Pat#    | Action     | Date
--------+------------+----------
123456  | Sim        | 3/5/2014
123456  | DosiFusion | 3/6/2014
123456  | MDRX       | 3/7/2014
123456  | TxEnd      | 3/10/2014
123456  | Sim        | 3/22/2014
123456  | DosiFusion | 3/22/2014
123456  | MDApproval | 3/24/2014
123456  | TxEnd      | 3/28/2014
3210032 | Sim        | 3/5/2014
3210032 | RTT Review | 3/6/2014
3210032 | TxEnd      | 3/10/2014

I want to have this data go into a crosstab that looks like this Columns are not matching with data but it should be clear what I want to do.

PatientId Sim       DosiFusion MDApproval MDRX      RTTReview TxEnd
--------- --------  ---------- ---------- --------  --------- ---------
123456    3/5/2014  3/6/2014   ---------  3/7/2014  --------- 3/10/2014
123456    3/22/2014 3/22/2014  3/24/2014  --------- --------- 3/28/2014
3210032   3/5/2014  ---------  ---------  --------- 3/6/2014  3/10/2014
هل كانت مفيدة؟

المحلول

Try a table rotation, something like this:

select sim.patient_id as "Pat#"       ,
       sim.Date       as "Sim"        ,
       dos.Date       as "DosFusion"  ,
       mda.Date       as "MDApproval" ,
       mdx.Date       as "MDRX"       ,
       rtt.Date       as "RTTREview"  ,
       txe.Date       as "TxEnd"
from ( select *
       from my_table
       where Action = 'Sim'
     ) sim
left join my_table dos on dos.action      = 'DosiFusion'
                      and dos.patient_id  = sim.patient_id
                      and dos.Date       >= sim.Date
left join my_table mda on mda.action      = 'MDApproval'
                      and mda.patient_id  = p.patient_id
                      and mda.Date       >= coalesce(dos.Date,sim.Date)
left join my_table mdx on mdx.action      = 'MDRX'
                      and mdx.patient_id  = p.patient_id
                      and mdx.Date       >= coalesce(mda.Date,dos.Date,sim.Date)
left join my_table rtt on rtt.action      = 'RTT Review'
                      and rtt.patient_id  = p.patient_id
                      and rtt.Date       >= coalesce(mdx.Date,mda.Date,dos.Date,sim.Date)
left join my_table txe on txe.action      = 'TxEnd'
                      and txe.patient_id  = p.patient_id
                      and txe.Date       >= coalesce(rtt.Date,mdx.Date,mda.Date,dos.Date,sim.Date)
order by 1,2,3,4,5,6,7

نصائح أخرى

In order to get data in shape of crosstab In sql You must use pivot table query Check this link sql server pivot table

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top