繁体   English   中英

SQL 服务器循环遍历列

[英]SQL server Looping through columns

我有一个包含多列的表,我想检查是否有多少列的值大于 5,如下所示。 你能帮忙吗? 谢谢, HHC

do i=1 to last_collumn;
 if column(i)>5 then count=count+1;
end;



Create TABLE have1  (
    id number(32),
    set1_a varchar(225),
    set1_b varchar(225),    
    set1_c varchar(225),
    set2_x varchar(225),
    set2_y varchar(225),    
    set3_n varchar(225)   
);
Insert into have1 (id,set1_a,set1_b,set1_c,set2_x,set2_y,set3_n) values (1,1,-333,200,1,1,'avb');
Insert into have1 (id,set1_a,set1_b,set1_c,set2_x,set2_y,set3_n) values (2,1,3,0,10,20,'ADULT');
Insert into have1 (id,set1_a,set1_b,set1_c,set2_x,set2_y,set3_n) values (2,1,3,0,1,1,'student');

尝试这个:

架构:

 Create TABLE have1 ( id int, set1_a varchar(225), set1_b varchar(225), set1_c varchar(225), set2_x varchar(225), set2_y varchar(225), set3_n varchar(225) ); Insert into have1 (id,set1_a,set1_b,set1_c,set2_x,set2_y,set3_n) values (1,1,-333,200,1,1,'avb'); Insert into have1 (id,set1_a,set1_b,set1_c,set2_x,set2_y,set3_n) values (2,1,3,0,10,20,'ADULT'); Insert into have1 (id,set1_a,set1_b,set1_c,set2_x,set2_y,set3_n) values (2,1,3,0,1,1,'student');

询问:

 select *, (case when set1_a>5 then 1 else 0 end + case when set1_b>5 then 1 else 0 end + case when set1_c>5 then 1 else 0 end + case when set2_x>5 then 1 else 0 end + case when set2_y>5 then 1 else 0 end ) Count_Of_Column_greater_than_5 from have1

Output:

编号 | set1_a | set1_b | set1_c | set2_x | set2_y | set3_n | Count_Of_Column_greater_than_5 -: |:----- |:----- |:----- |:----- |:----- |:------ | -----------------------------------------: 1 | 1 | -333 | 200 | 1 | 1 | 影音 | 1 2 | 1 | 3 | 0 | 10 | 20 | 成人 | 2 2 | 1 | 3 | 0 | 1 | 1 | 学生 | 0

db<> 在这里摆弄

您尚未标记您的 RDBMS,因此这可能需要也可能不需要一些调整

select Sum(
    Iif(set1_a>5, 1, 0)+
    Iif(set1_b>5, 1, 0)+
    Iif(set1_c>5, 1, 0)+
    Iif(set2_x>5, 1, 0)+
    Iif(set2_y>5, 1, 0)
) as TotalColumnsWithValueGreaterThan5
from have1

结果:3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM