我正在尝试从一个数据库获取数据并将其放在第二个数据库的格式中,其中模式不同。我正在尝试将一个表的多行中的数据放入一行,并使用一些逻辑来更改字段名称。我将有一个唯一的ID(encounterID),它将是结果表中的一个键,并且是多行中的外键。
这是我想要的输出模式,临时表:
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所在的位置('Rv','Lv','RvLv','Atrial')和EncounterID相同,并且LeadID是该字段中每行的唯一键,并且不需要在结果表中。
在我的情况下,每个EncounterID在#tmpLeads中通常只有两行,但LeadValues可以是上面任何两个不同的LeadValues(从不是两个'Lv',两个'Rv'或'RvLv等,但是'Lv'和'Atrial',或'Atrial'和'RvLv'。)
所以,最后,我的问题:
如何选择#tmpLeads中的值来更新#tmpSurgery,以便我根据LeadValue更新相应的值,所以我有一行?
答案 0 :(得分: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中查看。