SQL 个早于日期的 table 交易,但最近没有

SQL transactions within a table older than date, but doesn't have any lately

我有两个 table,InvMaster 和 InvMovements。我需要找到所有早于 x 个月的移动,但仅限于自 x 个月以来没有移动的行。主要日期字段是 InvMovements.EntryDate

InvMovements 是所有库存交易的集合。 StockCode 在 InvMaster table 中当然是唯一的,在 InvMovements 中是 1 对多。

这是我到目前为止整理的内容。

SELECT Inv.StockCode, MAX(Inv.EntryDate) as EntryDt
FROM InvMaster AS IM 
LEFT JOIN InvMovements AS Inv 
  ON IM.StockCode = Inv.StockCode 
--This gets us all the rows that have had JX transactions in the last x months 
RIGHT JOIN (SELECT IM.StockCode, MAX(IMv.EntryDate) As EntryDate 
            FROM InvMaster AS IM 
            LEFT JOIN InvMovements AS IMv 
              ON IM.StockCode = IMv.StockCode
            WHERE IMv.StockCode LIKE 'JX%' 
              AND IMv.EntryDate >= DATEADD(m, (-24), GETDATE())  
               OR IMv.EntryDate IS NULL
            GROUP BY IM.StockCode) AS MovedStock 
  ON MovedStock.StockCode != Inv.StockCode 
WHERE Inv.StockCode LIKE 'JX%' 
  AND Inv.EntryDate <= DATEADD(m, (-24), GETDATE()) 
   OR IM.StockCode LIKE 'JX%' AND Inv.EntryDate IS NULL
GROUP BY Inv.StockCode

听起来您只需要在 WHERE 条件中使用 NOT EXISTS。

我试着清理一下你的 where 条件,因为它对我来说没有意义。

SELECT  IM.StockCode,
        MAX(Inv.EntryDate) AS EntryDt
FROM    InvMaster AS IM
        LEFT JOIN InvMovements AS Inv ON IM.StockCode = Inv.StockCode 
WHERE   IM.StockCode LIKE 'JX%'
        AND (Inv.EntryDate <= DATEADD(m,(-24),GETDATE())
                OR Inv.EntryDate IS NULL)
        AND NOT EXISTS (
            SELECT  1
            FROM    InvMovements AS MovedStock
            WHERE   IM.StockCode = MovedStock.StockCode
                    AND MovedStock.EntryDate >= DATEADD(m,(-24),GETDATE())
        )
GROUP BY IM.StockCode

您想要 JX 股票代码早于特定月数的所有变动,但前提是它们在特定月数后没有变动。对于此示例,它将为您提供超过 6 个月的移动(WHERE CLAUSE),但前提是它们在最近 3 个月内没有移动(HAVING CLAUSE)。如果您真的希望这些数字始终相同,只需使用相同的变量即可。

DECLARE @olderThanMonths TINYINT = 6
    ,@sinceMonths TINYINT = 3

SELECT Inv.StockCode, MAX(Inv.EntryDate) as EntryDt
FROM InvMovements AS MO
    JOIN InvMaster AS MA
        ON MO.StockCode = MA.StockCode
WHERE MO.EntryDate <= DATEADD(MONTH,@olderThanMonths,GETDATE())
    AND MA.StockCode LIKE 'JX%'
GROUP BY Inv.StockCode
HAVING MAX(Inv.EntryDate) <= DATEADD(MONTH,@sinceMonths,GETDATE())