分组记录和排除

时间:2016-11-24 07:39:30

标签: sql sql-server

我有一个表名为Products with columns:

ProductID int, 
ProductName varchar(50), 
FromDate DATETIME, 
ToDate DATETIME, 
Modified DATETIME,
ModifiedBy int

此表包含相同的ProductNamesModified也是date类型列,用于说明Modified date对产品所做的任何更改。如果对产品ToDate进行任何更改,Modified将根据其他更改进行更新,则null

现在我的要求是:

  • 我希望productname ToDate有一个值 以及两列中的null
  • 排除那些Productname但没有变化意味着只有ToDateModifiedNULL
  • 需要Loca和Mocca的结果集

我试过这段代码

select  *     
from     Products cpp with (nolock)  
where   (TODATE is not null and Modfied is not null)        
        or (TODATE is null and Modified is null)  
order by ProductID desc

Table Data

2 个答案:

答案 0 :(得分:0)

我认为你的问题有点含糊不清。尝试这个,即使结果不会在两列中带来双重空值,但它将消除未完全修改的productname:

select  productname, todate, modified
from    Products
group by productname, todate, modified
having sum(case when (TODATE is not null and Modfied is not null) then 1 else 0 end) > 0

答案 1 :(得分:0)

    select  *     
    from   Products cpp with (nolock)  
    where NOT (TODATE is not null and Modfied is  null)        
    order by ProductID desc