2017-08-30 126 views
-1

我正在使用以下代码来尝试UNION两组数据,虽然它运行时没有错误,但它运行超过10分钟并且没有返回结果,所以我想知道是否有某种东西我做错了吗?在查询和子查询中使用SQL中的UNION

select BIH.SourceCode, BIH.MarketValueAmt as CorrectedAmt 
from [dbo].[IRA_HIST] as BIH 
JOIN 
    (select accountno, accountclass 
    from accounttable 
    where accountclass in ('A','B','C','D')) AS AccountNos 
ON BIH.ACCOUNTNO = ACCOUNTNOS.ACCOUNTNO 
where BIH.securityno > '0' 
UNION 
SELECT SourceCode, (Amount*(-1)) as CorrectedAmt 
from accttable a, activitytable b 
where a.accountclass in ('A','B','C','D') 
and b.recordtype in ('r','c') 

任何指导都非常有帮助。

+3

查看执行计划。 –

+0

不幸的是,我没有在我的公司查看他们的权限/访问权限。 – SMBRADBE

+3

然后得到它。如果您没有权限执行查询,则无需调试查询。 –

回答

0

在你的第二个选择,因为你查询两次相同的表,你应该能够加入一个公共密钥(例如FROM TABLE a JOIN TABLE b ON a.cKey = b.cKey)。

或者,您可以简化第二SELECT

FROM TABLE WHERE AccountClass IN ('A', 'B',...) OR RecordType IN ('r', 'c')

1

由于在从accounttable数据不需要其他的计算和转换,您可以直接与ira_hist加入它,没有必要有子查询。此外,您需要将其设置为ON。[key column] = b。[key column] - 可能在您的第二个查询中加入您的帐号no

SELECT BIH.SourceCode, 
     BIH.MarketValueAmt AS CorrectedAmt 
    FROM [dbo].[IRA_HIST] BIH 
    JOIN accounttable AccountNos 
    ON BIH.ACCOUNTNO = ACCOUNTNOS.ACCOUNTNO 
    AND BIH.securityno > '0' 
    AND AccountNos.accountclass in ('A','B','C','D') 
UNION -- or UNION ALL if you want to retain duplicates 
SELECT SourceCode, 
     (Amount*(-1)) as CorrectedAmt 
    FROM accttable a, 
    JOIN activitytable b 
    ON a.[key column] = b.[key column] -- probably accountno 
    AND a.accountclass IN ('A','B','C','D') 
    AND b.recordtype IN ('r','c')