无法检索到正确的结果

时间:2017-06-20 19:28:45

标签: sql select group-by

我有一个关于我正在处理的SQL脚本的问题

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的企业,但是我的第一个问题是它将所有状态为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到我的第一个选择?

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

而不是Left Join使用内部联接,因为它只会在公司打开时给出记录。另外,我在Sub查询中使用了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

如果您有任何问题,请告诉我

答案 1 :(得分: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

告诉我它是否适合你

答案 2 :(得分:0)

在您的JOIN子查询中,您添加了过滤器 businessstatus&lt;&gt; 3 以排除ID 3.但这是LEFT JOIN。在这种情况下,它将带来第一个表格,在您的案例公司和加载中的所有内容。

用内部连接替换LEFT JOIN。

LEFT JOIN是否还有其他正当理由。

答案 3 :(得分:0)

虽然你在子查询中给出了where条件(businessstatus&lt;&gt; 3),但它只过滤子查询,所以如果你用子查询做左连接,它会返回左表加右表的结果某行显示空列(在这种情况下(businessstatus == 3将为Null)

使用内部联接而不是左联接可以给出bussinessstatus&lt;&gt;的结果3