sql 获取多个列的总值

sql get total of value across multiple columns

我有一个 sql 服务器 2012 数据库 table 10 列

name test1, test2, test3, test4,....
 bob  yes    no    null    yes
 john  no    yes    yes    null

我想从 'test' 字段中获得所有结果的总和,所以我希望我的结果是

yes = 4
no = 2
null = 2

我试过使用 cte、sum、case when 但我无法得到我正在寻找的结果。下面是我的 sql 示例,如果有人可以告诉我如何获得我正在寻找的结果。

       with cte as 
  (
SELECT
test1,
sum (case when test1 = 'yes' then 1 else 0 end) as yes,
sum (case when test1= 'no' then 1 else 0 end) as no,
sum (case when test1 is null then 1 else 0 end) as notset
from names
group by Inspection1Type)
  select 
   sum (yes) as 'yes',
    sum(no) as 'no'
     sum(notset) as 'Not Set'
  from cte;

它适用于第一列,但不适用于其余列,因为我正在寻找相同的值,它抱怨我的别名相同

试试这种剪切和粘贴方法:

SELECT
    sum (case when test1 = 'yes' then 1 else 0 end
        +case when test2 = 'yes' then 1 else 0 end
        +case when test3 = 'yes' then 1 else 0 end
        ...
        +case when test10 = 'yes' then 1 else 0 end) as yes,
    sum (case when test1 = 'no' then 1 else 0 end
        +case when test2 = 'no' then 1 else 0 end
        +case when test3 = 'no' then 1 else 0 end
        ...
        +case when test10 = 'no' then 1 else 0 end) as no,
    sum (case when test1 is null then 1 else 0 end
        +case when test2 is null then 1 else 0 end
        +case when test3 is null then 1 else 0 end
        ...
        +case when test10 is null then 1 else 0 end) as notset
from names

我喜欢用 apply 处理这个问题。如果你想要每个 name 一行:

select n.*, v.*
from names n cross apply
     (select sum(case when v.test = 'yes' then 1 else 0 end) as yes,
             sum(case when v.test = 'no' then 1 else 0 end) as no,
             sum(case when v.test is null then 1 else 0 end) as nulls             
      from (values (n.test1), (n.test2), . . . (n.test10)) v(test)
     ) v;

如果您想要一行包含所有数据:

select sum(case when v.test = 'yes' then 1 else 0 end) as yes,
       sum(case when v.test = 'no' then 1 else 0 end) as no,
       sum(case when v.test is null then 1 else 0 end) as nulls 
from names n cross apply
     (values (n.test1), (n.test2), . . . (n.test10)) v(test);

在 table 中有重复的列通常表示数据模型存在问题。通常,您希望每个 name/test 一行,这将简化对此数据的查询。

试试这个:

WITH ABC
as
(
SELECT 'bob' as name, 'yes' as test1, 'no' as test2, null as test3, 'yes' as test4
UNION ALL
SELECT 'john', 'no','yes','yes',null
)
SELECT SUM(CASE WHEN A.result = 'yes' then 1 else 0 end) as [Yes], 
       SUM(CASE WHEN A.result = 'no' then 1 else 0 end) as [No],
       SUM(CASE WHEN A.result is null then 1 else 0 end) as [Null]
FROM 
(
    SELECT  name,result
    FROM ABC
    CROSS APPLY(VALUES(test1),(test2),(test3),(test4))  --may add up to test10
    COLUMNNAMES(result)
) as A