2011-12-01 42 views
1

我試圖從一個數據庫中獲取數據,並將其置於第二個數據庫的格式中,其中模式不同。我試圖將一個表的多行中的數據變成單行,並用一些邏輯來改變字段名稱。我將有一個唯一的ID(encounterID),它將成爲結果表中的一個鍵,並且是多行中的外鍵。用於將行移動到表中的列的SQL查詢以及別名

這是我想要的輸出模式,一個臨時表:

CREATE TABLE #tmpSurgery 
(  
EncounterID INT NULL, 
RvAmplitude DECIMAL(7,2) NULL, 
RvImpedance DECIMAL(7,2) NULL, 
RvPulseWidth DECIMAL(7,2) NULL, 
RvVoltage DECIMAL(7,2) NULL, 
RvCurrent DECIMAL(7,2) NULL, 
LvAmplitude DECIMAL(7,2) NULL, 
LvImpedance DECIMAL(7,2) NULL, 
LvPulseWidth DECIMAL(7,2) NULL, 
LvVoltage DECIMAL(7,2) NULL, 
LvCurrent DECIMAL(7,2) NULL, 
RvLvAmplitude DECIMAL(7,2) NULL, 
RvLvImpedance DECIMAL(7,2) NULL, 
RvLvPulseWidth DECIMAL(7,2) NULL, 
RvLvVoltage DECIMAL(7,2) NULL, 
RvLvCurrent DECIMAL(7,2) NULL, 
AtrialAmplitude DECIMAL(7,2) NULL, 
AtrialImpedance DECIMAL(7,2) NULL, 
AtrialPulseWidth DECIMAL(7,2) NULL, 
AtrialVoltage DECIMAL(7,2) NULL, 
AtrialCurrent DECIMAL(7,2) NULL 
) 

注意到有與前綴RV-,LV-,RvLv-和Atrial-振幅,脈衝寬度,阻抗,電壓和領域當前在不同的列。我的源表#tmpLeads有以下欄目:

LeadID 
EncounterID 
LeadValue 
Amplitude 
PulseWidth 
Impedance 
Voltage 
Current 

凡LeadValue是(「旅行車」,「呂」,「RvLv」,「房」)和EncounterID是相同的,並且LeadID是唯一的關鍵對於字段中的每一行,並且不需要在結果表中。

在我的情況下,每個EncounterID通常只有兩行#tmpLeads,但是LeadValues可以是上面任何兩個不同的LeadValues(從來沒有兩個'Lv's,兩個'Rv'或'RvLv's等等,但一個「呂」和「房」,或「房」和「RvLv」)

所以,最後,我的問題:

如何選擇值超出#tmpLeads的更新#tmpSurgery,以便根據LeadValue更新適當的值,所以我有一行?

回答

2

這應該工作:

INSERT INTO #tmpSurgery 
(
    EncounterID, 
    RvAmplitude, 
    RvImpedance, 
    RvPulseWidth, 
    RvVoltage, 
    RvCurrent, 
    LvAmplitude, 
    LvImpedance, 
    LvPulseWidth, 
    LvVoltage, 
    LvCurrent, 
    RvLvAmplitude, 
    RvLvImpedance, 
    RvLvPulseWidth, 
    RvLvVoltage, 
    RvLvCurrent, 
    AtrialAmplitude, 
    AtrialImpedance, 
    AtrialPulseWidth, 
    AtrialVoltage, 
    AtrialCurrent 
) 

SELECT 
    tblDistinct.EncounterID, 
    tblRv.Amplitude, 
    tblRv.Impedance, 
    tblRv.PulseWidth, 
    tblRv.Voltage, 
    tblRv.[Current], 
    tblLv.Amplitude, 
    tblLv.Impedance, 
    tblLv.PulseWidth, 
    tblLv.Voltage, 
    tblLv.[Current], 
    tblRvLv.Amplitude, 
    tblRvLv.Impedance, 
    tblRvLv.PulseWidth, 
    tblRvLv.Voltage, 
    tblRvLv.[Current], 
    tblAtrial.Amplitude, 
    tblAtrial.Impedance, 
    tblAtrial.PulseWidth, 
    tblAtrial.Voltage, 
    tblAtrial.[Current] 
FROM (SELECT DISTINCT EncounterID FROM #tmpLeads) as tblDistinct 
LEFT OUTER JOIN #tmpLeads as tblRv 
    ON tblRv.EncounterID = tblDistinct.EncounterID 
    AND tblRv.LeadValue = 'Rv' 
LEFT OUTER JOIN #tmpLeads as tblLv 
    ON tblLv.EncounterID = tblDistinct.EncounterID 
    AND tblLv.LeadValue = 'Lv' 
LEFT OUTER JOIN #tmpLeads as tblRvLv 
    ON tblRvLv.EncounterID = tblDistinct.EncounterID 
    AND tblRvLv.LeadValue = 'RvLv' 
LEFT OUTER JOIN #tmpLeads as tblAtrial 
    ON tblAtrial.EncounterID = tblDistinct.EncounterID 
    AND tblAtrial.LeadValue = 'Atrial' 

檢查它在行動here on SEDE

+0

非常感謝,並感謝您向我介紹DataExplorer。很酷的東西。 –