我有一个SQL Server数据库,其中包含一个包含20列的表。这些列具有同意或不同意的数据。现在我想在这些列中显示有"同意"其中的数据。我可以使用where子句,但对于20列来说这是一项耗时的任务。我正在寻找一个执行此任务的SQL查询。
答案 0 :(得分:2)
您可以使用in
:
select t.*
from t
where 'agree' in (col1, col2, ... col20);
答案 1 :(得分:1)
此类场景没有快捷方式,如果要比较所有列,则必须明确提及每一列,如。
WHERE Col1='agree' AND Col2="agree"....
为了避免编码,您可以使用动态查询创建或创建函数,但最终它将作为比较所有列的相同查询执行。
答案 2 :(得分:0)
JOIN
怎么样?
如果你有这么复杂的逻辑,最佳实践建议将数据保存在不同的表中。
答案 3 :(得分:0)
这是一些简化的示例代码,用于测试几种返回可能会或可能不同意的记录的方法。
实际上只是为了它的乐趣。
declare @T table (id int identity(1,1) primary key, col1 varchar(30), col2 varchar(30), col3 varchar(30));
insert into @T (col1, col2, col3) values
('agree','agree','agree'),
('agree','disagree','disagree'),
('agree','disagree',null),
('disagree','disagree','disagree'),
('disagree','disagree',null),
(null,null,null);
select 'OR' as method, * from @T
where (col1='agree' OR col2='agree' OR col3='agree');
select 'AND' as method, * from @T
where (col1='agree' AND col2='agree' AND col3='agree');
select 'IN' as method, * from @T
where 'agree' IN (col1, col2, col3);
select 'NOT IN' as method, * from @T
where 'agree' NOT IN (col1, col2, col3);
select 'LIKE' as method, * from @T
where CONCAT('-',col1,'-',col2,'-',col3,'-') LIKE '%-agree-%';
select 'NOT LIKE' as method, * from @T
where CONCAT('-',col1,'-',col2,'-',col3,'-') NOT LIKE '%-agree-%';
select 'ALL' as method, * from @T
where 'agree' = ALL(select col from (values (col1),(col2),(col3))q(col));
select 'SOME' as method, * from @T
where 'agree' = SOME(select col from (values (col1),(col2),(col3))q(col));
select 'ANY' as method, * from @T
where 'agree' = ANY(select col from (values (col1),(col2),(col3))q(col));
select 'EXISTS' as method, * from @T
where EXISTS (
select 1
from (values (col1),(col2),(col3))q(col)
where col = 'agree'
);
select 'NOT EXISTS' as method, * from @T
where NOT EXISTS (
select 1
from (values (col1),(col2),(col3))q(col)
where col = 'agree'
);