我正在编写一个查询,我需要根据几列中的内容返回一个标签。以下是列示例。
我需要返回的是所有在代理商列中只有a1的帐户,然后分配未指定的标签,其中a1在其中一个代理商列中,另一个代理商名称(ex a3)在一个在其他列中,将分配部分指定的标签。
下面的将是结果的列。
[结果标签] [2]
基本的IIF或Switch功能似乎无法满足需求,因为每个标签都有多个标准可以满足。
附加表信息。 Additional Table information
答案 0 :(得分:0)
为了在Access中获得所需的结果,我会尝试解除第一个表的转动,并获得每个代理商的最小值和最大值:
SELECT A.[Account#], MIN(A.Agency) AS MinAgency, MAX(A.Agency) AS MaxAgency
FROM
(
SELECT B.[Account#], B.Agency1 AS Agency
FROM SourceTable AS B
UNION
SELECT C.[Account#], C.Agency2
FROM SourceTable AS C
UNION
SELECT D.[Account#], D.Agency3
FROM SourceTable AS D
) AS A
GROUP BY A.[Account#]
我可能将此查询保存为" MinMaxAgencyQuery"然后用它来创建我的"字母类型"柱。 然后,我将在联合查询中构建此列,如下所示:
SELECT E.[Account#], "Undesignated" AS [Letter Type]
FROM SourceTable AS E LEFT JOIN MinMaxAgencyQuery AS A ON E.[Account#] = A.[Account#]
WHERE MinAgency = "a1" AND MaxAgency = "a1"
UNION
SELECT E.[Account#], "PartiallyDesignated" AS [Letter Type]
FROM SourceTable AS E LEFT JOIN MinMaxAgencyQuery AS A ON E.[Account#] = A.[Account#]
WHERE MinAgency = "a1" AND MaxAgency <> "a1"
UNION
SELECT E.[Account#], "Designated" AS [Letter Type]
FROM SourceTable AS E LEFT JOIN MinMaxAgencyQuery AS A ON E.[Account#] = A.[Account#]
WHERE MinAgency > "a1"
当然,这个解决方案依赖于&#34; a1&#34;实际上是&#34; a1&#34; (因此,在进行字符串比较时,比其他代理商少。)
如果我需要在同一个查询中执行所有操作,我会在三个联合查询中的每一个中替换我的第一个查询,如下所示:
SELECT E.[Account#], "Undesignated" AS [Letter Type]
FROM SourceTable AS E LEFT JOIN (
SELECT A.[Account#], MIN(A.Agency) AS MinAgency, MAX(A.Agency) AS MaxAgency
FROM
(
SELECT B.[Account#], B.Agency1 AS Agency
FROM SourceTable AS B
UNION
SELECT C.[Account#], C.Agency2
FROM SourceTable AS C
UNION
SELECT D.[Account#], D.Agency3
FROM SourceTable AS D
) AS A
GROUP BY A.[Account#]
) AS F ON E.[Account#] = F.[Account#]
WHERE MinAgency = "a1" AND MaxAgency = "a1"
UNION
SELECT E.[Account#], "PartiallyDesignated" AS [Letter Type]
FROM SourceTable AS E LEFT JOIN (
SELECT A.[Account#], MIN(A.Agency) AS MinAgency, MAX(A.Agency) AS MaxAgency
FROM
(
SELECT B.[Account#], B.Agency1 AS Agency
FROM SourceTable AS B
UNION
SELECT C.[Account#], C.Agency2
FROM SourceTable AS C
UNION
SELECT D.[Account#], D.Agency3
FROM SourceTable AS D
) AS A
GROUP BY A.[Account#]
) AS F ON E.[Account#] = F.[Account#]
WHERE MinAgency = "a1" AND MaxAgency <> "a1"
UNION
SELECT E.[Account#], "Designated" AS [Letter Type]
FROM SourceTable AS E LEFT JOIN (
SELECT A.[Account#], MIN(A.Agency) AS MinAgency, MAX(A.Agency) AS MaxAgency
FROM
(
SELECT B.[Account#], B.Agency1 AS Agency
FROM SourceTable AS B
UNION
SELECT C.[Account#], C.Agency2
FROM SourceTable AS C
UNION
SELECT D.[Account#], D.Agency3
FROM SourceTable AS D
) AS A
GROUP BY A.[Account#]
) AS F ON E.[Account#] = F.[Account#]
WHERE MinAgency > "a1"
您从未指定过没有代理商1,代理商2和代理商3的帐户的内容,因此在给定此解决方案的情况下不会显示这些内容。