1

我下面的查询返回计数大于 1 的所有记录。

我需要进一步定义查询以删除所有像 ProdNo 具有 TYPE DR 的记录和/或如果 PN 有 91535

示例 137818 由于有 DR,我不想显示任何记录。
示例 137763 由于有 91535,我不想显示任何记录。

----------------------------------------------------------------------------
ProdNo  Type    PN  Timestamp
137818  DF  91020       2012-08-07 00:54:19.000
137818  DR  91020       2012-08-07 07:57:51.000
137764  DF  91020       2012-08-05 23:13:34.000
137764  DF  91020       2012-08-05 23:25:20.000
137763  DF  91020       2012-08-05 22:58:36.000
137763  DF  91535       2012-08-06 02:26:38.000
----------------------------------------------------------------------------

示例 137764 由于没有 DR 或 91535,我希望显示 1 条记录。

----------------Desired-Results---------------------------------------------
ProdNo  Type    PN  
137764  DF  91020
----------------------------------------------------------------------------

查询根据计数查找 Prod 记录

declare @usetime datetime;
set @usetime =  ( dateadd( dd, -2, getdate() ))
SELECT ProdNo, Type, PN
  FROM [ProdStat].[dbo].[Prod]
  -- limit results to ProdNo's < 200000 for Products numbers up to 1999999 and > @usetime
  WHERE Timestamp > @usetime AND ProdNo < '200000' and ProdNo IN(
  select ProdNo
 FROM [ProdStat].[dbo].[Prod]
 group by ProdNo
 having (COUNT(ProdNo) >1)
 )
 order by ProdNo desc
4

2 回答 2

1

这应该为您的示例数据执行此操作:

declare @usetime datetime; 
set @usetime =  ( dateadd( dd, -2, getdate() )) 
SELECT ProdNo, Type, PN 
  FROM [ProdStat].[dbo].[Prod] 
  -- limit results to ProdNo's < 200000 for Products numbers up to 1999999 and > @usetime 
  WHERE Timestamp > @usetime AND ProdNo < '200000' and ProdNo IN( 
     select ProdNo 
     FROM [ProdStat].[dbo].[Prod]
      group by ProdNo 
      having (COUNT(ProdNo) >1) 
  ) 
  AND ProdNo NOT IN (
     SELECT ProdNo FROM [ProdStat].dbo.Prod WHERE Type = 'DR' OR PN = 91535
  )
  order by ProdNo desc
于 2012-08-07T15:05:27.620 回答
0

这是一个比较简单的方法:

declare @usetime datetime;
set @usetime =  ( dateadd( dd, -2, getdate() ))
SELECT ProdNo, Type, PN
FROM [ProdStat].[dbo].[Prod]
-- limit results to ProdNo's < 200000 for Products numbers up to 1999999 and > @usetime
WHERE Timestamp > @usetime AND ProdNo < '200000' and
      ProdNo IN (select ProdNo
                 FROM [ProdStat].[dbo].[Prod]
                 group by ProdNo
                 having COUNT(ProdNo) >1) and
                        max(case when type = 'DR' then 1 else 0 end) = 0 and
                        max(case when PN = 91535 then 1 else 0 end) = 0
                )
order by ProdNo desc
于 2012-08-07T15:14:26.483 回答