sql - 有条件地计算一行中的项目
问题描述
想要计算一行中满足条件列表的项目数,并将结果放在行的 errorcnt 列中。实际数据有大约 15 个条件和一百列。我认为这个样本应该说明我所追求的。
CREATE TABLE #MyList
(
Item1 NVARCHAR(100),
Item2 NVARCHAR(100),
date1 DATE,
Date2 date,
errorcnt int
)
INSERT INTO #MyList
(
Item1,
Item2,
Date1,
Date2
)
VALUES
('Dog','Puppy', '2020-01-01', '2030-01-01'),
('Cat', 'Kitten', '2020-02-02', '2020-03-03')
要计数的样本条件:
When Item1 <> Dog, OR
when Item2 <> puppy, OR
when Date2>date1
这些中的每一个都将被计算在内,以便记录#2,
Item1 <> Dog = 1
Item2 <> puppy = 1
Date 2 > Date 1 = 1
Total 3 errors.
第 2 行的输出为:
Cat, Kitten, 2020-02-02, 2020-03-03, 3
新手,不知道如何做到最好。
解决方案
使用case
表达式:
select ml.*,
( (case when Item1 <> 'Dog' then 1 else 0 end) +
(case when when Item2 <> 'puppy' then 1 else 0 end) +
(case when Date2 > date1 then 1 else 0 end)
) as total_errors
from #mylist ml;
推荐阅读
- c# - 让所有列表条目出现在第二个 wpf 应用程序上
- r - GGanimate:带有数值的 geom_text 以十进制数字而不是整数进行动画处理
- python - 使用 tensorflow 后端指定 GPU ID
- c# - Identity Server (OpenID Connect) 混合流程:需要用户使用刷新令牌保持登录状态 5 年
- javascript - 为什么不应该使用内联 JavaScript?
- google-assistant-sdk - 谷歌嵌入式助手服务在包含时给出关于 text_config 缺失的错误
- python - Pandas 将两个数据帧相乘得到乘积
- wordpress - 按功能更改 xml 自定义提要后出错
- java - 在java中将不同的对象添加到列表中
- java - Java / Jackson - 'Unrecognized token' 传递 JSON 对象参数