下面必须有更好的方法来编写查询,如果您有任何建议,请告诉我。
SELECT *
FROM
[eSDR_Full].[dbo].[course_register]
WHERE
broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND end_month is null
AND disabled <> 'Y'
OR broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND end_month > '201512'
AND disabled <> 'Y'
OR broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND end_month is null
AND disabled is null
OR broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND end_month > '201512'
AND disabled is null
ORDER BY
end_month DESC
答案 0 :(得分:2)
首次重构:
SELECT *
FROM [eSDR_Full].[dbo].[course_register]
Where (broad_field_code = '08' and narrow_field_code = '05' and detail_field_code = '05')
and ( (end_month is null and disabled <> 'Y')
or (end_month > '201512' and disabled <> 'Y')
or (end_month is null and disabled is null)
or (end_month > '201512' and disabled is null))
order by end_month desc
这清楚地表明您对所有条件都有一个共同的前缀。
第二次重构利用了其他共性:
SELECT *
FROM [eSDR_Full].[dbo].[course_register]
Where (broad_field_code = '08' and narrow_field_code = '05' and detail_field_code = '05')
and (end_month is null or end_month > '201512')
and (disabled is null or disabled <> 'Y')
order by end_month desc
现在很明显,我们只是根据每个列的简单条件有一系列堆叠的AND,所以我们可以这样做:
SELECT *
FROM [eSDR_Full].[dbo].[course_register]
Where broad_field_code = '08'
and narrow_field_code = '05'
and detail_field_code = '05'
and coalesce(end_month, '999999') > '201512'
and coalesce(disabled, 'N') <> 'Y')
order by end_month desc
答案 1 :(得分:0)
这应该有效:
SELECT *
FROM [eSDR_Full].[dbo].[course_register]
WHERE broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND (end_month IS NULL OR end_month > '201512')
AND ISNULL(disabled,'') != 'Y'
ORDER BY end_month DESC