首页 > 解决方案 > 有条件地计算一行中的项目

问题描述

想要计算一行中满足条件列表的项目数,并将结果放在行的 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

新手,不知道如何做到最好。

标签: sqlsql-server

解决方案


使用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;

推荐阅读