2013-03-25 129 views
0

我有表名爲PATIENTINFO和MEDICATIONINFO的柱子下面列行冬眠

PATIENTINFO 

PatiendId  Disease 
------------------------ 
1000   Fever 
1001   Cold 


MEDICATIONINFO 

MedId  PatiendId Medicine  Value Reaction 
------------------------------------------------------ 
100   1000   Med1  100  R 
101   1000   Med2  200  L 
102   1000   Med3  150  H 
103   1001   Med1  120  L 
104   1001   Med2  150  R 
105   1001   Med3  300  H 

我想結果是在下面的格式(休眠查詢)提到

Medicine Value1  Reaction1  Value2  Reaction2 .......(Value n ...Reaction n) 
---------------------------------------------------------------- 
Med1   100   R  120   L 
Med2   200   L  150   R 
Med3   150   H  300   H 

誰能幫助我在這裏?

+1

你嘗試過什麼嗎? – BobTheBuilder 2013-03-25 22:29:09

+0

這種東西被稱爲'數據透視'查詢。 – 2013-03-25 22:58:03

回答

0
SELECT 
    MINFO.Medicine, 
    MINFO.Reaction1, 
    SUM(CASE WHEN MINFO.Reaction = 'R' THEN Value ELSE 0 END) Value1, 
    SUM(CASE WHEN MINFO.Reaction = 'L' THEN Value ELSE 0 END) Value2, 
    SUM(CASE WHEN MINFO.Reaction = 'H' THEN Value ELSE 0 END) Value3, 
FROM PATIENTINFO PINFO 
    LEFT JOIN MEDICATIONINFO MINFO 
     ON PINFO.PatiendId = MINFO.PatiendId 
GROUP BY MINFO.Reaction