我有两张桌子:patient_allergens
prob_person_id allergens
-------------- ---------
123 NO KNOWN ALLERGIES
和patient_medication
med_person_id med_start_date medication_name
------------- -------------- ---------------
123 20140819 Seroquel 50 mg tablet
123 20140819 trazodone 50 mg tablet
123 20140825 clonazepam 2 mg tablet
123 20150407 duloxetine 60 mg capsule,delayed release
123 20160222 atorvastatin 40 mg tablet
当我加入桌子时,我得到了:
select pa.prob_person_id,
pa.allergens,
pm.med_person_id,
pm.med_start_date,
pm.medication_name
from patient_allergens pa
left join patient_medication pm on pa.prob_person_id = pm.med_person_id
prob_person_id allergens med_person_id start_date medication_name
-------------- --------- ------------- ---------- ---------------
123 NO KNOWN ALLERGIES AF469E7B-3115-4715-8561-8088192D8AEE 20140819 Seroquel 50 mg tablet
123 NO KNOWN ALLERGIES AF469E7B-3115-4715-8561-8088192D8AEE 20140819 trazodone 50 mg tablet
123 NO KNOWN ALLERGIES AF469E7B-3115-4715-8561-8088192D8AEE 20140825 clonazepam 2 mg tablet
123 NO KNOWN ALLERGIES AF469E7B-3115-4715-8561-8088192D8AEE 20150407 duloxetine 60 mg capsule,delayed release
123 NO KNOWN ALLERGIES AF469E7B-3115-4715-8561-8088192D8AEE 20160222 atorvastatin 40 mg tablet
我不确定如何修改连接以获得具有NULL
的以下结果集prob_person_id allergens med_person_id start_date medication_name
-------------- --------- ------------- ---------- ---------------
123 NO KNOWN ALLERGIES AF469E7B-3115-4715-8561-8088192D8AEE 20140819 Seroquel 50 mg tablet
NULL NULL NULL 20140819 trazodone 50 mg tablet
NULL NULL NULL 20140825 clonazepam 2 mg tablet
NULL NULL NULL 20150407 duloxetine 60 mg capsule,delayed release
NULL NULL NULL 20160222 atorvastatin 40 mg tablet
答案 0 :(得分:1)
您可以使用Rank()
来实现此目标。
--Setup test data
DECLARE @alergen TABLE (Name VARCHAR(16))
DECLARE @med TABLE (Name VARCHAR(16))
INSERT INTO @alergen
SELECT 'peanuts'
INSERT INTO @med
SELECT 'acetomenophene'
UNION
SELECT 'ibuprofen'
--Show how rank will assign a row number to each record
SELECT RANK() OVER (ORDER BY name)
, Name
FROM @alergen
SELECT RANK() OVER (ORDER BY name)
, Name
FROM @med
--Combine the ranking queries to get the desired result
SELECT *
FROM (
SELECT RANK() OVER (ORDER BY name) AS 'row_number'
, Name
FROM @alergen
) alergens
-- Use FULL JOIN so that all records are included even if there are row_numbers in one list that aren't in the other
FULL JOIN (
SELECT RANK() OVER (ORDER BY name) AS 'row_number'
, Name
FROM @med
) meds ON alergens.row_number = meds.row_number