Sql Server 2000:返回“ true”或“假”基于25列中的任何一列是“ true”
-
06-07-2019 - |
题
我必须创建一个检查多个不同列的查询,如果其中任何一个有1,我想返回true。
理想的输出将是:
ID:55,点击
姓名:John Doe
IsDealerType1:真正的结果
IsDealerType2:真正的结果
IsDealerType3:虚假点击
IsDealerType4:虚假点击
IsDealerType5:True
问题是,我有大约20个名为1a,1b,1c,1d等的列,而不是那5个经销商列。如果“1”中有任何一列。列为true,则IsDealerType1应为true。
我试图避免在VB.NET代码中写一些东西来检查每一列,只是因为在SQL中应该很容易避免这种简单的丑陋 - 只要我知道怎么做 - 但我是不确定如何构造查询。我一直在尝试像...这样的东西。
SELECT id,
name,
(1a or 1b or 1c or 1d) as IsDealerType1,
(2a or 2b or 2c or 2d) as IsDealerType2
where id = 55
......但显然,我做得不对。
感谢任何帮助。谢谢!
解决方案
我喜欢罗素,但我也会加上这个:
CASE WHEN 1 IN (1a,1b,1c,1d) THEN 1 ELSE 0 END As IsDealerType1
其他提示
情况(1a + 1b + 1c + 1d)> 0 THEN 1 ELSE 0 END为IsDealerType1
使用SQL 按位OR 运算符。避免比较和演员表。
示例:Joel的答案将整数1或0传递给客户端,在那里你可以期待bit(boolean)。 Remus的答案需要演员和比较。
SELECT id,
name,
(1a | 1b | 1c | 1d) as IsDealerType1,
(2a | 2b | 2c | 2d) as IsDealerType2
where id = 55
在SQL中,BIT类型不能在布尔表达式中使用(d'oh !!),它们需要与int进行比较:
SELECT id, name,
cast(
case when ([1a]=1 or [1b]=1 or [1c]=1 or [1d]=1) then 1 else 0 end
as bit) as IsDealerType1,
cast(case when ([2a]=1 or [2b]=1 or [2c]=1 or [2d]=1) then 1 else 0 end
as bit) as IsDealerType2
from [table]
where id = 55
不隶属于 StackOverflow