简体   繁体   中英

sql get results from one column with the name of another column

Sorry for the title I'm not sure how to word my question.

I have 3 tables Info , Description , Encounter .

Info :

Patient_NO   ENCOUNTER_NO   Problem_1
1                1             V707
1                2             V343
2                3             P567

Description :

Problem_Description   Problem_Code
Cold                     V707
Knee Pain                V343
Headache                 P567

Encounter :

Patient_NO ENCOUNTER_NO
1               1
1               2
2               3

How this works is someone creates an encounter and they enter a problem then it gets saved to the patient. a patient can have multiply encounters.

I'm trying to select Problem_1 and then join it on problem code, but I want it to display the problem description and not the actual code itself. But I only want it to display the problem that was entered in that specific encounter.

If this makes sense to anyone or I can try explaining better.

This works in SQL Server, other RDBMS should be similar...

DECLARE @Info TABLE(Patient_NO INT,ENCOUNTER_NO INT,Problem_1 VARCHAR(100));
INSERT INTO @Info VALUES
 (1,1,'V707')
,(1,2,'V343')
,(2,3,'P567');

DECLARE @Description TABLE(Problem_Description VARCHAR(100),Problem_Code VARCHAR(100));
INSERT INTO @Description VALUES 
 ('Cold','V707')
,('Knee Pain','V343')
,('Headache','P567');

DECLARE @Encounter TABLE(Patient_NO INT, ENCOUNTER_NO INT);
INSERT INTO @Encounter VALUES
 (1,1)
,(1,2)
,(2,3);

SELECT e.ENCOUNTER_NO 
      ,i.Patient_NO 
      ,i.Problem_1
      ,d.Problem_Description 
FROM @Encounter AS e
INNER JOIN @Info AS i ON e.Patient_NO=i.Patient_NO AND e.ENCOUNTER_NO=i.ENCOUNTER_NO
INNER JOIN @Description AS d ON i.Problem_1 = d.Problem_Code 

The result:

1   1   V707    Cold
2   1   V343    Knee Pain
3   2   P567    Headache

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM