You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查询仅含transaction code 10、无对应配对关联行的invoice记录

解法1:GROUP BY + HAVING 聚合过滤

假设你的表名为invoice_trans,写法如下:

SELECT `Transaction Code`, `Invoice Number`
FROM invoice_trans
WHERE `Invoice Number` IN (
    SELECT `Invoice Number`
    FROM invoice_trans
    WHERE `Transaction Code` IN (10, 11)
    GROUP BY `Invoice Number`
    HAVING COUNT(DISTINCT `Transaction Code`) = 1 
    AND MAX(`Transaction Code`) = 10
)
AND `Transaction Code` = 10;

逻辑说明:子查询先筛选所有涉及交易码10、11的发票,按发票编号分组后,过滤出仅存在1种交易码且该交易码为10的发票编号,外层查询再对应取出交易码为10的记录即可。

如果你的实际排查逻辑是校验是否同时存在10和20,仅保留仅含10的记录,把上面SQL中的11替换为20即可。


解法2:NOT EXISTS 关联过滤(适合大数据量场景,性能更优)

SELECT t1.`Transaction Code`, t1.`Invoice Number`
FROM invoice_trans t1
WHERE t1.`Transaction Code` = 10
AND NOT EXISTS (
    SELECT 1
    FROM invoice_trans t2
    WHERE t2.`Invoice Number` = t1.`Invoice Number`
    AND t2.`Transaction Code` = 11
);

逻辑说明:直接查询交易码为10的记录,同时校验同发票编号下不存在交易码为11的记录,直接返回符合要求的结果。


内容的提问来源于stack exchange,提问作者KCS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:45:07