如果不满足连接条件,如何显示null

时间:2016-09-29 05:55:37

标签: sql sql-server sql-server-2008 tsql

我有一个表tbl_expenseLimit,用于获取给定变量组合的Limit

tbl_expenselimit

+------+---------+----------+---------+-------+----------+
| SrNo | ExpType | Location | Expense | Limit | empgrade |
+------+---------+----------+---------+-------+----------+
|    1 | ERA     | Metro    |       1 |   250 | A        |
|    2 | ERA     | Metro    |       2 |   500 | A        |
|    3 | ERA     | Metro    |       3 |  5000 | A        |
+------+---------+----------+---------+-------+----------+

如果主表中的ExpType为ERA,Location为Metro,Expense为1,empgrade为'A',则Limit为250 。

如果任何条件不匹配,例如:如果ExpType为ERA,Expense为1,则empgrade为“A”,但Location为非然后Metro Limit应为NULL。同样,如果所有条件都匹配但是升级为'B'(tbl_expenselimit表中不存在,那么它应该NULL返回Limit

select other.srno,VoucherId,other.ExpType, lmt.Limit 
from tbl_voucherotherexpense other 
left join tbl_TypesOfExpenses expensemst 
on other.expense=expensemst.srno 
left   join tbl_expenseLimit lmt 
on (other.Expense=lmt.Expense 
and other.ExpType=lmt.ExpType     
and (( lmt.location is not null  
and other.location=lmt.location) or 1=1))   
where voucherid='C0000004' and lmt.empgrade='a'

tbl_voucherotherexpensetbl_TypesOfExpenses之间的联接始终会找到匹配项。所以需要关注的只是tbl_expenseLimit

我写的查询错了。它没有实现我想要的。任何帮助表示赞赏。

修改

假设在我的主要表ExpType ERA Location Metro Expense 2 但是empgrade B 然后输出应该是:

+------+-----------+---------+-------+
| srno | VoucherId | ExpType | Limit |
+------+-----------+---------+-------+
|    4 | C0000004  | ERA     | NULL  |
+------+-----------+---------+-------+

或者如果 在我的主要表ExpType ERA Location Metro empgrade A 但{ {1}} 12 然后输出仍应与上述相同。

1 个答案:

答案 0 :(得分:0)

引用您即将加入的表格lmt的所有条件都应该放在on中,与where条款不同,它会赢得&#t} t删除条件不匹配的行:

select other.srno,VoucherId,other.ExpType, lmt.Limit 
from tbl_voucherotherexpense other left join tbl_TypesOfExpenses expensemst on other.expense=expensemst.srno 
left join tbl_expenseLimit lmt 
    on other.Expense=lmt.Expense 
    and other.ExpType=lmt.ExpType 
    and other.location=lmt.location   
    and lmt.empgrade='a' 
where voucherid='C0000004'