我有一个场景,我有4列-SUBBRAND,COLLECTIONS,PLCYCLE,COLORFAMILY,并且我必须为记录分配优先级:
要编写一个包含所有可能组合的case语句是完成此操作的唯一方法,还是有任何简单的方法来做到这一点?
示例代码:
CASE WHEN SUBBRAND IS NOT NULL AND COLLECTIONS IS NOT NULL
AND PLCYCLE IS NOT NULL AND COLORFAMILY IS NOT NULL
THEN 1 AS PRIORITY,
WHEN SUBBRAND IS NOT NULL AND COLLECTIONS IS NOT NULL
AND PLCYCLE IS NOT NULL OR
WHEN COLLECTIONS IS NOT NULL AND PLCYCLE IS NOT NULL
AND COLORFAMILY IS NOT NULL OR
WHEN PLCYCLE IS NOT NULL AND COLORFAMILY IS NOT NULL
AND WHEN SUBBRAND IS NOT NULL OR
so on....
THEN 2 AS PRIORITY
and other conditions..
END PRIORITY
在此先感谢您的帮助!
答案 0 :(得分:1)
在Oracle中,空字符串值被视为NULL
,因此您只需要检查NULL
。
如果NVL2
和0
使用NULL
产生1
,否则:
SELECT
5 - (
NVL2(SUBBRAND, 1, 0) +
NVL2(COLLECTIONS, 1, 0) +
NVL2(PLCYCLE, 1, 0) +
NVL2(COLORFAMILY, 1, 0)
) AS Priority
我想所有4列都不是NULL。
答案 1 :(得分:0)
也许首先计算NULL值:
SELECT 1 /* highest priority */ +
/* increase priority for each non-empty value */
+ NVL2(SUBBRAND, 0, 1) + NVL2(COLLECTIONS, 0, 1) + NVL2(PLCYCLE, 0, 1) + NVL2(COLORFAMILY, 0, 1)
AS PRIORITY
...
正如dlatikay所注意到的:如果所有值都为空,则必须决定如何处理。在上述解决方案中,优先级将变为5,这就是您想要的吗?
答案 2 :(得分:0)
NVL2()
很方便。但是,如果“空白”允许空格或其他字符,则需要case
逻辑。我会去的:
SELECT (1 +
NVL2(TRIM(' ' FROM SUBBRAND), 0, 1) +
NVL2(TRIM(' ' FROM COLLECTIONS), 0, 1) +
NVL2(TRIM(' ' FROM PLCYCLE), 0, 1) +
NVL2(TRIM(' ' FROM COLORFAMILY), 0, 1)
) AS Priority
答案 3 :(得分:0)
发布对我有用的最终代码(某种)。 感谢大家的帮助,也非常感谢您为您提供的所有帮助:))
SELECT U, V, W, X, Y, Z, SUBBRAND, COLLECTIONS, PLCYCLE, COLORFAMILY,
CASE
WHEN ABC = 1
THEN (SELECT MAX (5 /* highest priority */ +
/* increase priority for each non-empty value */
+ NVL2(SUBBRAND, 0, 1) + NVL2(COLLECTIONS, 0, 1) + NVL2(PLCYCLE, 0, 1) +
NVL2(COLORFAMILY, 0, 1)) PRIORITY
FROM T1)
WHEN ABC = 0
THEN (SELECT MAX (9 /* highest priority */ +
/* increase priority for each non-empty value */
+ NVL2(SUBBRAND, 0, 1) + NVL2(COLLECTIONS, 0, 1) + NVL2(PLCYCLE, 0, 1) +
NVL2(COLORFAMILY, 0, 1)) PRIORITY
FROM T1)
END PRIORITY, ABC
FROM T1
WHERE NVL2(SUBBRAND, 1, 0) + NVL2(COLLECTIONS, 1, 0) + NVL2(PLCYCLE, 1, 0) +
NVL2(COLORFAMILY, 1, 0) > 0;
如果可以建议对该查询进行任何性能调整,这将非常有帮助:D
数据量大约为100 M或更多。