美好的一天。我有一个名为subObjGroup
的表。我从这个表中选择并针对几个列执行case语句。我正在查看typeCol
列,以便对要使用的适当嵌套大小写操作符进行分类。
问题在于,当它执行该语句时,我收到vCheck
列的错误结果。我没有根据案例陈述标准获得数据。不确定我做错了什么。当numid和value相同时,是否有幕后的“钩子”或“链接”?任何帮助都非常感谢。
在vCheck
列
groupid eventid numid tagVal greaterThan greaterEqThan lessThan lessEqThan equalTo typeCol vCheck activeid getVal
28 18 9000001 NULL NULL NULL 105 NULL NULL 3 1 68 92.907
9 19 9000001 NULL NULL NULL 105 NULL NULL 3 1 68 92.907
10 20 9000001 NULL 105 NULL NULL NULL NULL 1 0 68 92.907
所需结果请查看vCheck
列
groupid eventid numid tagVal greaterThan greaterEqThan lessThan lessEqThan equalTo typeCol vCheck activeid getVal
28 18 9000001 NULL NULL NULL 105 NULL NULL 3 0 68 92.907
9 19 9000001 NULL NULL NULL 105 NULL NULL 3 0 68 92.907
10 20 9000001 NULL 105 NULL NULL NULL NULL 1 1 68 92.907
剧本
DECLARE @nID nvarchar(50)
SET @nID = '9000001'
SELECT
g.groupid,
g.eventid,
g.numid,
g.tagVal,
g.greaterThan,
g.greaterEqThan,
g.lessThan,
g.lessEqThan,
g.equalTo,
g.typeCol,
vCheck =
CASE
WHEN g.typecol = 0 THEN CASE
WHEN g.getVal = g.tagval THEN 0
ELSE 1
END
WHEN g.typecol = 1 THEN CASE
WHEN g.getVal > g.greaterthan THEN 0
ELSE 1
END
WHEN g.typecol = 2 THEN CASE
WHEN g.getVal >= g.greatereqthan THEN 0
ELSE 1
END
WHEN g.typecol = 3 THEN CASE
WHEN g.getVal < g.lessthan THEN 0
ELSE 1
END
WHEN g.typecol = 4 THEN CASE
WHEN g.getVal <= g.lesseqthan THEN 0
ELSE 1
END
WHEN g.typecol = 5 THEN CASE
WHEN g.getVal = g.equalto THEN 0
ELSE 1
END
ELSE 0
END,
g.activeid,
g.getVal
FROM subobjgroup g
WHERE numid = @nID
答案 0 :(得分:2)
我认为逻辑只是向后(你在子句中混淆了“1”和“0”)。
但是,我认为这种逻辑更简单地写成:
vCheck = (CASE WHEN g.typecol = 0 AND g.getVal = g.tagval THEN 1
WHEN g.typecol = 1 AND g.getVal > g.greaterthan THEN 1
WHEN g.typecol = 2 AND g.getVal >= g.greatereqthan THEN 1
WHEN g.typecol = 3 AND g.getVal < g.lessthan THEN 1
WHEN g.typecol = 4 AND g.getVal <= g.lesseqthan THEN 1
WHEN g.typecol = 5 AND g.getVal = g.equalto THEN 1
ELSE 0
END),