我需要2个表来验证某些信息,例如:
表A(GTM_LICENSE):
License ID (PK) - License Category
123 - PURCHASE
456 - SALES
表B(GTM_LICENSE_INVOLVED_PARTY):
License ID (PK) - Involved Party Type
123 - SUPPLIER X
456 - CUSTOMER X
但是,我需要验证以下内容: 购买许可证必须始终至少有一个供应商记录。销售许可证必须始终至少有一个CUSTOMER记录。
我可以执行2个不同的查询,甚至只能执行1个查询,一次检查这两个条件。没关系。但是,如果条件为真(购买许可证有供应商或销售许可证有客户),我的预期结果将为“1”,如果条件为假,则为null。
我正在尝试运行以下查询,但这对我不起作用。
SELECT 1 FROM GTM_LICENSE L
INNER JOIN GTM_LICENSE_INVOLVED_PARTY LI
ON LI.LICENSE_GID = L.LICENSE_GID
WHERE LI.INVOLVED_PARTY_QUAL_GID IN ('CUSTOMER','SUPPLIER')
AND L.LICENSE_CATEGORY_GID IN ('SALES','PURCHASE')
GROUP BY L.LICENSE_GID
HAVING COUNT(*) > 0
如何使用Oracle SQL执行此操作?有什么建议吗?
由于
答案 0 :(得分:0)
select l.license_gid,
l.license_category_gid,
(select max(1) from gtm_license_involved_party li
where li.license_gid = l.license_gid
and ((li.involved_party_qual_gid = 'CUSTOMER'
and l.license_category_gid = 'SALES')
or (li.involved_party_qual_gid = 'SUPPLIER'
and l.license_category_gid = 'PURCHASE'))
) valid_party
from gtm_license l
;
答案 1 :(得分:0)
我相信这会让您获得不符合要求的许可证列表:
SELECT L.LICENSE_GID
FROM GTM_LICENSE L LEFT OUTER JOIN GTM_LICENSE_INVOLVED_PARTY LI
ON LI.LICENSE_GID = L.LICENSE_GID AND
(
L.LICENSE_CATEGORY_GID = 'PURCHASE'
AND LI.INVOLVED_PARTY_QUAL_GID = 'SUPPLIER'
OR
L.LICENSE_CATEGORY_GID = 'SALES'
AND LI.INVOLVED_PARTY_QUAL_GID = 'CUSTOMER'
)
WHERE
GROUP BY L.LICENSE_GID
HAVING COUNT(LI.LICENSE_GID) = 0;
这可能比复杂的连接条件更直接:
SELECT L.LICENSE_GID
FROM GTM_LICENSE L
WHERE NOT EXISTS (
SELECT 1 FROM GTM_LICENSE_INVOLVED_PARTY LI
WHERE LI.LICENSE_GID = L.LICENSE_GID AND
(
L.LICENSE_CATEGORY_GID = 'PURCHASE'
AND LI.INVOLVED_PARTY_QUAL_GID = 'SUPPLIER'
OR
L.LICENSE_CATEGORY_GID = 'SALES'
AND LI.INVOLVED_PARTY_QUAL_GID = 'CUSTOMER'
)
);
这将为您提供包含每个许可证指标的结果集。它与kfinity的答案几乎相同。我没有使用聚合函数折叠到标量值,而是使用可以说更具可读性的case
表达式:
SELECT L.LICENSE_GID
CASE WHEN NOT EXISTS (
SELECT 1 FROM GTM_LICENSE_INVOLVED_PARTY LI
WHERE LI.LICENSE_GID = L.LICENSE_GID AND
(
L.LICENSE_CATEGORY_GID = 'PURCHASE'
AND LI.INVOLVED_PARTY_QUAL_GID = 'SUPPLIER'
OR
L.LICENSE_CATEGORY_GID = 'SALES'
AND LI.INVOLVED_PARTY_QUAL_GID = 'CUSTOMER'
)
) THEN 1 ELSE NULL END AS INDICATOR
FROM GTM_LICENSE L;