左外部联接到表的前1行

时间:2019-02-11 23:42:36

标签: sql tsql

我有以下查询。我想在帐单的第一行与明细表具有相同键的情况下离开外部联接。

SELECT e.id,a.empid,CASE WHEN ISNULL(bill.key,0) <> 0 Then 'Yes'
      ELSE 'No' END as billing  
from
(SELECT customer, accountid from employee e, account a where e.Id = a.empId) w, 
detail d LEFT outer join billing bill
        on bill.key = d.key

WHERE d.detailid = w.accountID

问题:计费表可以有多个键,但是我只想将一个键连接到明细表。我正在尝试查找它是否包含账单密钥。现在,左外部联接无法正常工作,因为它返回多个结果,因此我的查询未返回正确的结果。

1 个答案:

答案 0 :(得分:0)

使用外部应用

   SELECT e.id,a.empid,CASE WHEN ISNULL(bill.key,0) <> 0 Then 'Yes'
          ELSE 'No' END as billing  
    FROM
    (SELECT customer, accountid from employee e, account a where e.Id = a.empId) w, 
    detail d OUTER APPLY (SELECT Top 1 key FROM billing bill2 where bill2.key = d.key) bill


    WHERE d.detailid = w.accountID