SQL:检查值是否在组中退出,如果为true,则仅返回true

时间:2018-09-03 12:53:46

标签: sql-server

假设我有下表

ExampleTable

id ¦ value
--------------
1  ¦ True
1  ¦ False
2  ¦ False
3  ¦ True
3  ¦ False

我知道所有id都将为False,但是我想要的输出是,如果存在True,则只给我True行。基本上;

id ¦ value
--------------
1  ¦ True
2  ¦ False
3  ¦ True

我该怎么做?

我尝试过:

select 
    *
from 
    ExampleTable
group by 
    id
having 
    max(case value when 'True' then 1 else 0 end) = 0

但这会删除所有错误或所有真实。

预先感谢

3 个答案:

答案 0 :(得分:3)

由于'True'的字母顺序比'False'大,所以您可以这样做

select id, max(value) as value
from ExampleTable
group by id

但是您实际上应该将TRUE / FALSE值存储为bit而不是文本数据类型。

答案 1 :(得分:0)

select * 
from TestDb 
where value=1 
union 
select * 
from testDb 
where value=0 
     and id not in
          (select id from TestDb where value=1)

答案 2 :(得分:0)

在复杂的查询中,

Select  * from
(
 select *,Row_Number(partition by by id order by value desc)rn from ExampleTable

)tbl
where rn=1

另一个查询

Select top 1 * from
(
select *,1 Priority from ExampleTable
where value='True'

union all

select *,2 Priority from ExampleTable
where value='False'
)tbl
order by  Priority