【问题标题】:SQL - LEFT OUTER JOIN ON BETWEEN RANGESQL - 范围之间的左外连接
【发布时间】:2021-01-25 11:58:47
【问题描述】:

我需要加入 4 个表才能为每个 AccountID 找到正确的 AccountGroup。

问题是当我尝试在我的加入中使用“between”时,我得到了错误的 AccountGroup 引用。

我有以下表格:

表:帐户

AccountID AccountDesc
500050 Test

表:AccountDesc

AccountFromID AccountToID AccountGroup
500050 500050 OtherCost

表:AccountExtended

AccountID
500050
500050_Seller
500050_Purchaser

表:AccountExtendedDesc

AccountID AccountGrp1ID AccountGrp2ID AccountGroup
500050 500050_Seller 500050_A CostOfSeller
500050 500050_Purchaser 500050_A CostOfSeller

问题在于它返回的查询,我的 AccountGroup 错误为 500050,它同时返回了 OtherCost 和 CostOfSeller 的 GroupDescriptions。

表格:结果(错误)

AccountID AccountDesc
500050 CostOfSeller
500050 OtherCost
500050_Seller CostOfSeller
500050_Purchaser CostOfSeller

我只想要

AccountID AccountDesc
500050 OtherCost
500050_Seller CostOfSeller
500050_Purchaser CostOfSeller

我的查询

SELECT AE.AccountID, isnull(A.AccountGroup, Ad.AccountGroup) as AccountGroup FROM 
(
SELECT 
AE.AccountID,
Aed.AccountGroup

FROM Accounts A
RIGHT OUTER JOIN AccountExtended AE on left(AE.AccountID,6)=A.AccountID
LEFT OUTER JOIN AccountExtendedDesc Aed on Aed.AccGrp1ID= A.AccountID
) A

LEFT OUTER JOIN AccountDesc Ad on A.AccountID between Ad.AccountFromID and Ad.AccountToID

【问题讨论】:

  • 你使用的是什么 SQL 版本?
  • 我正在使用 V. 2017
  • A.ItemID 在 A 子查询中不存在,您的表中也没有这样的列
  • 已更新,应该是 AccountID。只是我这边打错字了。

标签: sql left-join between


【解决方案1】:

我不确定我是否理解每个表之间的关系。我下面的代码假定AccountExtendedDesc 表中的任何内容将基本上覆盖AccountDesc 表中的任何内容。我已经忽略了 Accounts 表,因为我完全不确定它是否需要。

SELECT
    ae.AccountID,
    isnull(aed.AccountGroup, ad.AccountGroup) as AccountGroup
FROM
    AccountExtended ae
    LEFT JOIN AccountDesc ad ON
        ae.AccountID between ad.AccountFromID AND ad.AccountToID
    LEFT JOIN AccountExtendedDesc aed ON
        aed.AccountGrp1ID = ae.AccountID

【讨论】:

    【解决方案2】:

    下面的查询给出了你需要的结果。

    SELECT A.AccountID, isnull(A.AccountGroup, Ad.AccountGroup) as AccountGroup FROM 
    (SELECT 
    AE.AccountID,
    Aed.AccountGroup
    
    FROM Accounts A
    RIGHT OUTER JOIN AccountExtended AE on left(AE.AccountID,6)=A.AccountID
    LEFT OUTER JOIN AccountExtendedDesc Aed on Aed.AccountGrp1ID= AE.AccountID
    ) A
    LEFT OUTER JOIN AccountDesc Ad on A.AccountID between Ad.AccountFromID and Ad.AccountToID
    

    【讨论】:

    • 我仍然得到 500050 的 CostOfSeller 和其他成本。与 between 的最后一个外部连接搞砸了。
    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    相关资源
    最近更新 更多