【发布时间】:2016-11-06 04:17:43
【问题描述】:
我有三张桌子:
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)
样本数据:
诊所
id region country continent area
3299 Kazakhstan Kazakhstan Eurasia Middle East/Asia
result_month
id year result_quarter_id month
200801 2008 2008Q1 1
test_value_in_range_count
clinic 表中没有诊所 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
我通过拆分尝试了很多不同的查询,但没有运气。任何帮助或指导将不胜感激。
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
;
【问题讨论】:
标签: sql sql-server left-join where-clause outer-join