我有如下记录:
Name Count
123456M2.txt NULL
123456M2.txt 15
123456M.txt NULL
您能指导我如何编写此查询。
我能够执行CASE-WHEN查询,但无法继续进行字母检查的IF ELSE条件
CASE
WHEN CHARINDEX('M', [FILE_NAME]) > 0 THEN 'COUNT'
答案 0 :(得分:4)
您需要为案例中的每个WHEN使用多个条件:
(伪代码)
WHEN {Name contains 'M'} AND {character after 'M' is a number} AND {Count is NULL or < 0} THEN NULL
WHEN {Name contains 'M'} AND {character after 'M' is a number} AND {Count is NULL or < 0} THEN 1
etc...
无需在查询中的任何地方添加IF..ELSE
逻辑。
答案 1 :(得分:2)
我将其表达为:
select . . .,
(case when name like '%M[0-9]%' and count > 0 then 1
when name like '%M[0-9]%' then 0
else "some number from another field"
end)
一个case
表达式按顺序计算条件,在第一个计算结果为“ true”的条件处停止。
您的描述有点不清楚,因为NULL
不是< 0
。
答案 2 :(得分:1)
尝试以下
DECLARE @TBL TABLE (Name VARCHAR(25), [Count] INT);
INSERT INTO @TBL VALUES
('123456M2.txt', NULL),
('123456M2.txt', 15),
('123456M.txt', NULL);
SELECT *,
CASE WHEN Name LIKE '%M[0-9]%' AND ([Count] IS NULL OR [Count] < 0) THEN --Check for NULL too cause NULL is not < 0
NULL
WHEN Name LIKE '%M[0-9]%' AND [Count] > 0 THEN
1
WHEN Name LIKE '%M.%' THEN
555 --Other value from other column
END AS Results
FROM @TBL;
结果:
+--------------+-------+---------+
| Name | Count | Results |
+--------------+-------+---------+
| 123456M2.txt | | |
| 123456M2.txt | 15 | 1 |
| 123456M.txt | | 555 |
+--------------+-------+---------+