sha*_*haz 0 sql sql-server left-join outer-join where-clause
我有三张表:
clinic = (id,name,short_name,region,country,continent,area)
result_month =(id,year,result_quarter_id,month)
test_value_in_range_count =(clinic_id,result_month_id,patient_sub_set_id,test_value_range_id,number_of_values)
Run Code Online (Sandbox Code Playgroud)
样本数据:
诊所
id region country continent area
3299 Kazakhstan Kazakhstan Eurasia Middle East/Asia
Run Code Online (Sandbox Code Playgroud)
结果月
id year result_quarter_id month
200801 2008 2008Q1 1
Run Code Online (Sandbox Code Playgroud)
test_value_in_range_count
诊所表中没有诊所 ID 3299 的数据。但是 JOINS 必须返回
我需要让result_month表中的所有行都带有test_value_in_range_count 中的空值。问题是WHERE条款。这将停止生成行,因为从result_month到test_value_range_id 的某些行显然不存在数据。
预期结果
clinic region country continent area ym vf
3299 Kazakhstan Kazakhstan Eurasia Middle East/Asia 201511 null
Run Code Online (Sandbox Code Playgroud)
我通过拆分它们尝试了很多各种查询,但没有运气。任何帮助或指导将不胜感激。
SELECT
apc.id AS clinic,
apc.region,
apc.country,
apc.continent,
apc.area,
vrm.id AS ym,
SUM(CASE test_value_range_id WHEN '1124_1' THEN number_of_values ELSE 0 END) AS avf
FROM result_month vrm
LEFT JOIN test_value_in_range_count vt on vrm.id = vt.result_month_id
LEFT OUTER JOIN clinic apc on vt.clinic_id = apc.id
WHERE (vt.test_value_range_id IN ('1124_1', '1124_2', '1124_3', '1124_4', '1124_5')) AND (vt.patient_sub_set_id = 'ALL')
GROUP BY apc.id,
apc.region,
apc.country,
apc.continent,
apc.area,
vrm.id
;
Run Code Online (Sandbox Code Playgroud)
从 where 子句中删除条件并将其添加到join:
SELECT
apc.id AS clinic,
apc.region,
apc.country,
apc.continent,
apc.area,
vrm.id AS ym,
SUM(CASE test_value_range_id WHEN '1124_1' THEN number_of_values ELSE 0 END) AS avf
FROM result_month vrm
LEFT JOIN test_value_in_range_count vt on vrm.id = vt.result_month_id and (vt.test_value_range_id IN ('1124_1', '1124_2', '1124_3', '1124_4', '1124_5')) AND (vt.patient_sub_set_id = 'ALL')
LEFT OUTER JOIN clinic apc on vt.clinic_id = apc.id
GROUP BY apc.id,
apc.region,
apc.country,
apc.continent,
apc.area,
vrm.id
;
Run Code Online (Sandbox Code Playgroud)
否则 where 子句join从你的left join
| 归档时间: |
|
| 查看次数: |
519 次 |
| 最近记录: |