sql跨多个列获取总值

时间:2018-05-14 13:45:15

标签: sql sql-server sum common-table-expression case-when

我有一个带有10列

的表的sql server 2012 db
name test1, test2, test3, test4,....
 bob  yes    no    null    yes
 john  no    yes    yes    null

我想从'测试'中获得所有结果。字段所以我希望我的结果是

yes = 4
no = 2
null = 2

我尝试过使用cte,sum,case但是我无法得到我正在寻找的结果。下面是我的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;

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

我喜欢用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);

在表格中重复列通常表明数据模型存在问题。通常情况下,您需要每name / test行一行,这样可以简化对此数据的查询。

答案 2 :(得分:0)

试试这个:

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