SQL select 列值作为自定义名称
SQL select column value as custom name
如果另一列等于特定值,我正在尝试将数据提取到新列中。
我的数据是不同的电信值存储在同一列中,另一个描述符列指定它是电子邮件地址还是家庭 phone、手机等。我想将电子邮件拉入电子邮件列,家庭phone 到 homephone 列,移动到它自己的列,等等
我从 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'
谢谢!
您似乎需要条件聚合。逻辑是将聚合函数中的条件表达式移动到每个列的主元中,并将其他列放在 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
如果另一列等于特定值,我正在尝试将数据提取到新列中。
我的数据是不同的电信值存储在同一列中,另一个描述符列指定它是电子邮件地址还是家庭 phone、手机等。我想将电子邮件拉入电子邮件列,家庭phone 到 homephone 列,移动到它自己的列,等等
我从 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'
谢谢!
您似乎需要条件聚合。逻辑是将聚合函数中的条件表达式移动到每个列的主元中,并将其他列放在 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