sql - sql获取多列的总价值
问题描述
我有一个带有 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 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
推荐阅读
- c - (从文件中读取)C 中的链表
- html - CSS Radio 部分没有正确堆叠在顶部?
- chatbot - 在没有完成第一个意图的情况下处理在 alexa 中触发另一个意图
- python - 如何将数组更改为布尔值,使数组输出 True/False
- ios - 如何搜索在 Xcode 的 Images.xcassets 中创建的内容?
- php - 将if语句放入带参数的php函数中?
- sql - 使用 group by 或 join 时有何不同?
- python - 如何优化 django-import-export?
- java - Camel Jetty 使用 Spring Boot 端口
- java - Spring Boot REST:无法测试@RequestParam 的验证