SQL红移选择整表或一条记录动态选择问题
我有一个表,我想要动态选择: 如果条件列没有任何“坏”值,请选择整个表 如果存在任何“错误”,则打印具有错误值的行SQL红移选择整表或一条记录动态选择问题,sql,sql-server,tsql,sql-order-by,amazon-redshift,Sql,Sql Server,Tsql,Sql Order By,Amazon Redshift,我有一个表,我想要动态选择: 如果条件列没有任何“坏”值,请选择整个表 如果存在任何“错误”,则打印具有错误值的行 id, name, condition 1 apple good 2 pearl bad 3 kiwi good 4 grapes good 我考虑过使用union,但无法思考如何正确选择 如果表格是这样的,则打印整个表格 id, name, condition 1 apple good 2 pearl
id, name, condition
1 apple good
2 pearl bad
3 kiwi good
4 grapes good
我考虑过使用union,但无法思考如何正确选择
如果表格是这样的,则打印整个表格
id, name, condition
1 apple good
2 pearl good
3 kiwi good
4 grapes good
如果表格如下所示,则仅选择第3行
id, name, condition
1 apple good
2 pearl good
3 kiwi bad
4 grapes good
您可以使用
不存在
:
select t.*
from t
where not exists (select 1 from t t2 where t2.condition = 'bad');
您可以使用
不存在
:
select t.*
from t
where not exists (select 1 from t t2 where t2.condition = 'bad');
一个选项是
联合所有
和不存在
:
select t.* from mytable t where condition = 'bad'
union all
select t.* from mytable t where not exists (select 1 from mytable t1 where t1.condition = 'bad')
如果您运行的是SQL Server(您将其与amazon redshift一起标记),您也可以使用ties执行此操作:
select top (1) with ties t.*
from mytable t
order by case when condition = 'bad' then 0 else 1 end
一个选项是
联合所有
和不存在
:
select t.* from mytable t where condition = 'bad'
union all
select t.* from mytable t where not exists (select 1 from mytable t1 where t1.condition = 'bad')
如果您运行的是SQL Server(您将其与amazon redshift一起标记),您也可以使用ties执行此操作:
select top (1) with ties t.*
from mytable t
order by case when condition = 'bad' then 0 else 1 end