2017-06-20 103 views
0

我有一個問題,關於那我就無法檢索到正確的結果

SELECT distinct companyid, 
     companyshortname, 
     loanamount, 
     employeename, 
     , employeerole, 
     MaxTime, 
     businessdescription 
FROM  company 
INNER JOIN loan ON companyfkey = loanfkey 
LEFT JOIN (SELECT businessdescription_fkey, 
        MAX(w.business_date_transaction_occured) AS MaxTime 
      FROM businessdescription w 
      WHERE w.businessstatus <> 3 <-- this means that the company is still open 
      GROUP BY w.businessdescription_fkey) wf 
ON company_fkey = businessdescriotion_fkey 

工作這回我有一個狀態比3個不同的所有企業一個SQL腳本,但我的第一個問題是它返回給我的所有業務,確實有狀態3.

我的第二個問題是我將如何納入另一個值來跟蹤如Businessdescriptioncomment我會做這樣的事情?

LEFT JOIN (SELECT businessdescription_fkey, 
        MAX(w.business_date_transaction_occured) AS MaxTime , 
        w.businessdescriptioncomment AS BusinessComment 
      FROM businessdescription w   
      WHERE w.businessstatus <> 3 <-- this means that the company is open 
      GROUP BY w.businessdescription_fkey) wf 
ON company_fkey = businessdescriotion_fkey 

和我的變量BusinessComment到我的第一個選擇?

感謝您的任何幫助。

+0

您是否檢查過內部選擇? 它只是返回business = 3的行嗎? 如果是這樣,也許更改左加入INNER加入 –

+1

有一個雙','這裏:'employeename,,employeerole,' – McNets

+0

你的問題是不清楚..你有錯誤嗎? ...錯誤的結果...? .. – scaisEdge

回答

0

改變你的第二個加入這樣的:

INNER JOIN businessdescription w 
ON company_fkey = w.businessdescriotion_fkey 
and businessstatus <> 3 

在你選擇放:

SELECT distinct companyid, 
     companyshortname, 
     loanamount, 
     employeename, 
     employeerole, 
     MaxTime, 
     businessdescription, 
     w.businessdescriptioncomment 
FROM company 

告訴我,如果你的作品

0

在你JOIN子查詢,你添加過濾器businessstatus <> 3排除id 3。但這是一個左加入。在這種情況下,它將帶來第一張表格中的所有內容,包括您的案例公司和負載。

用INNER JOIN替換LEFT JOIN。

您是否有任何其他有效的LEFT JOIN原因。

1

而不是Left Join使用內部加入,因爲它只會給記錄公司如果打開。另外,我已經使用self join在子查詢來獲取Business Comment,然後用它在外部選擇查詢

試試這個: -

SELECT distinct companyid, 
     companyshortname, 
     loanamount, 
     employeename, 
     , employeerole, 
     MaxTime, 
     businessdescription, 
     BusinessComment 
FROM  company a 

INNER JOIN loan b 
ON a.companyfkey = b.loanfkey 

INNER JOIN 
(
    SELECT a.businessdescription_fkey, a.MaxTime, w.businessdescriptioncomment AS BusinessComment 
    FROM 
    (
    SELECT businessdescription_fkey, 
         MAX(w.business_date_transaction_occured) AS MaxTime 
       FROM businessdescription w   
       WHERE w.businessstatus <> 3 
       GROUP BY w.businessdescription_fkey 
    ) a 
    INNER JOIN 
    businessdescription w 
    ON a.businessdescription_fkey=w.businessdescription_fkey AND a.MaxTime=w.business_date_transaction_occured 
    WHERE w.businessstatus <> 3 
) c 
ON a.company_fkey = c.businessdescriotion_fkey 

讓我知道如果您有任何疑問

+0

謝謝你,作品! – artbarzz

+0

@ artbarzz歡迎您。樂於幫助。如果您喜歡解決方案,您可以接受。請訪問此鏈接https://stackoverflow.com/help/someone-answers瞭解更多信息 –

0

雖然你有在子查詢中給出where條件(businessstatus <> 3),它僅對子查詢進行篩選,因此如果使用子查詢進行左連接,則返回左表加右表的結果,其中某行顯示Null列(在此案例(businessstatus == 3將爲空)

使用內部連接而不是左連接可以給出bussinessstatus的結果<> 3