SQL 在其他行有条件地显示

SQL Display conditionally on other row

我有一个 table,其中列出了批号,然后是该批次通过的每个阶段的测试结果。

我想显示每个阶段的测试结果,但只显示过去 7 天内通过某个阶段的批次。

到目前为止,我的 WHERE 中有以下内容:

WHERE [DateTime] >= DATEDIFF(dd,7,GETDATE())
  AND Stage IN ('4','5')
  AND FVBatch LIKE '3%'

GROUP BY FVBatch, [DateTime], Stage, Brand

这显示了我想要显示的批次,但它只显示了最后 2 个阶段。我希望能够在阶段列上应用此条件,然后还显示这些批次的前 3 个阶段。

下图显示了上述查询的结果。我想要的是它还显示第 1、2 和 3 阶段的结果

只有 4 或 5 个批次

..
FROM ttable t1
WHERE [DateTime] >= DATEDIFF(dd,7,GETDATE()) -- are you sure? [DateTime] >= DATEADD(dd,-7,GETDATE())
  AND EXISTS (SELECT 1 FROM ttable t2 WHERE t2.FVBatch = t1.FVBatch AND t2.Stage IN ('4','5'))
  AND FVBatch LIKE '3%'

GROUP BY FVBatch, [DateTime], Stage, Brand
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT FVBatch, [DateTime], Stage, Brand       -- this inner query
    FROM yourTable                                 -- will retain only
    WHERE Stage IN ('4','5')                       -- groups having
    GROUP BY FVBatch, [DateTime], Stage, Brand     -- stages 4 and 5
    HAVING COUNT (DISTINCT Stage) = 2
) t2
    ON t1.FVBatch    = t2.FVBatch    AND
       t1.[DateTime] = t2.[DateTime] AND
       t1.Stage      = t2.Stage      AND
       t1.Brand      = t2.Brand
WHERE t1.[DateTime] >= DATEDIFF(dd,7,GETDATE()) AND
      t1.FVBatch LIKE '3%'