使用SQL Server中的GROUP BY过滤数据

时间:2014-08-15 12:30:43

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

我的表格数据类似

Id    value1    value2  IsIncluded
----------------------------------
1859    1702    4043    0
1858    1706    4045    0
1858    1703    4046    1
1860    1701    4046    0
1861    1702    4047    0

要使用min(value1)max(value2)获取ID并根据所包含的列进行过滤,我可以执行以下操作

select 
    Id, min(value1), max(value2)
from table
where IsIncluded = 0
group by Id

我得到了结果

Id    value1    value2  IsIncluded
-----------------------------------
1859    1702    4043    0
1858    1706    4045    0
1860    1701    4046    0
1861    1702    4047    0`

但如果{1}}中有1个用于该ID,我可以更多地过滤数据,那么它不应该选择该行。

5 个答案:

答案 0 :(得分:2)

select Id, min(value1), max(value2)
from table t
where t.IsYpIncluded=0
  and not exists (
  select 0 from table t2
  where t.Id = t2.Id
  and t2.IsYpIncluded = 1
)
group by t.Id;

答案 1 :(得分:1)

你可以试试这个,

select ID,min(Value1),max(Value2) from table
where ID not in(select distinct ID from table where IsYpIncluded=1)
group by ID

答案 2 :(得分:0)

嗯。我认为您要排除任何行中id的任何1。如果是这样,您可以使用having子句:

select Id, min(value1), max(value2)
from table
group by Id
having max(cast(IsYpIncluded as int)) = 0;

这假设IsYpIncluded永远不会消极,但基于问题中的数据似乎就是这种情况。

答案 3 :(得分:0)

选择Id,min(value1),max(value2) 从表 其中IsYpIncluded< 0 按ID分组

答案 4 :(得分:0)

与Gordon Linoff相似,这对我有用

选择Id,min(value1),max(value2) 从表 按ID分组 具有和(IsIncluded = 1然后1,0结束时的情况)= 0