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

SQL查询修改需求:获取含InventoryCosts无记录的LineItem数据

修改方案及说明

要满足你的需求,需要调整连接类型并扩展过滤条件,具体修改如下:

核心修改点

  • 将原查询的INNER JOIN改为LEFT JOIN,保留LineItem中无对应InventoryCosts记录的数据
  • 扩展WHERE条件,同时包含两类目标数据:原查询匹配到的有效成本记录,以及LineItem中满足Quantity=0且无对应InventoryCosts的记录

修改后的完整SQL

SELECT 
    I.ItemID, I.ItemDescription,
    C.RecordType, C.TransDate, C.PostOrderNumber,
    C.Quantity, C.TransAmount
FROM 
    LineItem I 
LEFT JOIN 
    InventoryCosts C ON I.ItemRecordNumber = C.ItemRecNumber
LEFT JOIN 
    (SELECT 
         ItemRecNumber, RecordType, 
         MAX(TransDate) AS lastDate, MAX(PostOrderNumber) AS LastEntry 
     FROM 
         InventoryCosts
     WHERE 
         RecordType = 50
     GROUP BY 
         ItemRecNumber, RecordType) S ON C.ItemRecNumber = S.ItemRecNumber 
                                      AND C.RecordType = S.RecordType 
                                      AND C.TransDate = S.lastDate 
                                      -- AND C.PostOrderNumber = S.LastEntry
WHERE 
    I.ItemIsInactive <> 1
    AND (
        -- 原逻辑:存在对应InventoryCosts且为最新记录
        (C.ItemRecNumber IS NOT NULL AND S.ItemRecNumber IS NOT NULL)
        -- 新增逻辑:无对应InventoryCosts且Quantity=0
        OR (C.ItemRecNumber IS NULL AND I.Quantity = 0)
    )
ORDER BY 
    I.ItemID

关键修改解释

  1. LEFT JOIN 替换 INNER JOIN:
    原INNER JOIN会自动过滤掉LineItem中没有匹配InventoryCosts的记录,改为LEFT JOIN后能保留这些无对应成本的记录,为筛选Quantity=0的条目提供基础。

  2. WHERE条件扩展:
    通过OR分支新增筛选逻辑,专门匹配“无对应InventoryCosts记录且Quantity=0”的LineItem,同时保留原查询中“有对应成本且为最新记录”的逻辑。

  3. 子查询的LEFT JOIN:
    子查询S用于匹配InventoryCosts中的最新记录,改为LEFT JOIN后,当C不存在时,S会返回NULL,不会干扰无对应成本记录的筛选。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:12:42