我在围绕如何编写在左连接上包含可选过滤器的过程时遇到问题。
我有两个表,问题和 Customer_Location。并非所有问题都与客户位置相关联。所以我认为这是一个起点:
SELECT
I.Issue_Number,
C.Customer_Location_Code
FROM Issues I
LEFT JOIN Customer_Location C
ON C.Customer_Location_Key = I.Customer_Location_Key
Issue_Number | Customer_Location_Code
1 | Chicago
2 | NULL
3 | Chicago
4 | New York
这有效,它给了我所有的问题。但我想为客户位置代码添加一个可选参数,如果留空将返回所有 4 个问题,但如果为芝加哥设置为 1,则仅返回问题 1 和 3。
我试过这个
DECLARE @customer_location_key INT
SET @customer_location_key = 1
SELECT
I.Issue_Number,
C.Customer_Location_Code
FROM Issues I
LEFT JOIN Customer_Location C
ON C.Customer_Location_Key = I.Customer_Location_Key
AND C.Customer_Location_Key = @customer_location_key
但我得到以下结果
Issue_Number | Customer_Location_Code
1 | Chicago
2 | NULL
3 | Chicago
4 | NULL
出于某种原因,我现在似乎在放屁,但似乎无法理解 应该 做一些比较简单的事情
最佳答案
添加一个类似于下面的 where 子句应该可以做到。
DECLARE @customer_location_key INT
SET @customer_location_key = 1
SELECT
I.Issue_Number,
C.Customer_Location_Code
FROM Issues I
LEFT JOIN Customer_Location C
ON C.Customer_Location_Key = I.Customer_Location_Key
where (@customer_location_key is null or C.Customer_Location_Key = @customer_location_key)
关于sql - 左连接列上的可选过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5332952/