【发布时间】: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。只是我这边打错字了。