0

如果另一列等于特定值,我正在尝试将数据提取到新列中。

我的数据是存储在同一列中的不同电信值,另一个描述符列指定它是电子邮件地址还是家庭电话、手机等。我想将电子邮件拉入电子邮件列,将家庭电话拉入家庭电话列,并将手机拉入自己的列栏目等

我从 CASE 开始,但不确定如何扩展它以使用第二列中的值:

select TOP 20 
    BF.fileID,  
    PT.Patient_DateOfBirth as DOB, 
    ContactType = 
        CASE CONT.Patient_Telecom_Use
            WHEN 'EM' THEN 'Email'
            WHEN 'HP' THEN 'HomePh'
            ELSE 'otherContact'
        END 
-- 'EM' is email, 'HP' is home phone, etc, need to figure out how to select CONT.Patient_Telecom_value into 'email' etc
    from  
        [BaseFile] BF  
    INNER JOIN [Patient] as PT 
        ON  BF.[fileId] = PT.[FileId]
    INNER JOIN [PatientTelecomunication] as CONT
        ON BF.[fileId] = CONT.[FileId]

如果我把它写成一个假设的 IF-THAN 语句,我会说:

IF 
Patient_Telecom_Use='EM' 
THEN select Patient_Telecom_value as 'email'

谢谢!

4

1 回答 1

0

您似乎想要条件聚合。逻辑是将聚合函数中的条件表达式移动到每个列以进行透视,并将其他列放在一个GROUP BY子句中,如下所示:

select TOP (20)
    BF.fileID,  
    PT.Patient_DateOfBirth as DOB, 
    MAX(CASE WHEN CONT.Patient_Telecom_Use = 'EM' THEN CONT.Patient_Telecom_value END) as Email,
    MAX(CASE WHEN CONT.Patient_Telecom_Use = 'HP' THEN CONT.Patient_Telecom_value END) as HomePh
FROM [BaseFile] BF  
INNER JOIN [Patient] as PT ON  BF.[fileId] = PT.[FileId]
INNER JOIN [PatientTelecomunication] as CONT ON BF.[fileId] = CONT.[FileId]
GROUP BY BF.fileID,  PT.Patient_DateOfBirth
于 2020-11-03T17:37:02.017 回答