我有一个表格,列出了批次编号,然后是该批次经过的每个阶段的测试结果。
我想显示每个阶段的测试结果,但仅限于过去7天内已经过一定阶段的批次。
到目前为止,我在我的WHERE中有以下内容:
WHERE [DateTime] >= DATEDIFF(dd,7,GETDATE())
AND Stage IN ('4','5')
AND FVBatch LIKE '3%'
GROUP BY FVBatch, [DateTime], Stage, Brand
这显示了我想要显示的批次,但它只显示最后两个阶段。我希望能够在舞台专栏上应用此条件,但随后还会显示这些批次的前3个阶段。
下图显示了上述查询的结果。我想要的是它还显示第1,2和2阶段的结果。 3
答案 0 :(得分:1)
只有批次为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
答案 1 :(得分:1)
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%'