TSQL Group by计数1列中的重复值,限制结果为第2列中的值&第3栏

时间:2012-08-07 14:55:19

标签: sql tsql

我的查询会返回所有计数超过1的记录。

我需要进一步定义查询以删除所有类似具有TYPE DR的ProdNo记录和/或如果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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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