2014-05-15 80 views
1

我聽說我需要一個數組。不知道這是什麼以及它如何適用於我的數據。任何幫助是極大的讚賞!在SQL中創建交叉表

我有我的查詢,看起來像這樣

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 
032 | Sim  | 3/5/2014 
032 | RTT Review | 3/6/2014 
032 | TxEnd  | 3/10/2014 

數據回來時,我想有這樣的數據進入一個交叉表,看起來像這樣 列不與數據進行匹配,但應該很清楚我想做。

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 
032 3/5/2014 --------- --------- --------- 3/6/2014 3/10/2014 
+4

請爲確切版本的SQL添加標籤。另請注意,大約1%的互聯網專門用於描述如何在SQL中執行交叉表的頁面。 –

回答

1

嘗試工作臺旋轉,像這樣:

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 
0

爲了獲得交叉 的形狀數據在SQL 您必須使用數據透視表查詢 檢查此鏈接 sql server pivot table