sql - 根据案例条件计算一列
问题描述
这是代码:
select sum(case when status_code= '200' then 1 else 0 end) as success,
sum(case when status_code!= '200' then 1 else 0 end ) as failure from my_table
输出:
success failure
1 2
仅当失败计数 < = 5 时,我才必须选择计数失败
解决方案
解决方案
添加有子句。
select sum(case when status_code= '200' then 1 else 0 end) as 'success',
sum(case when status_code!= '200' then 1 else 0 end) as 'failure'
from my_table
having sum(case when status_code!= '200' then 1 else 0 end) <= 5;
完整示例
结果:
declare @my_table table
(
status_code int
);
insert into @my_table (status_code) values
(200), (1), (1); --> 2 failures
select sum(case when status_code = 200 then 1 else 0 end) as 'success',
sum(case when status_code != 200 then 1 else 0 end) as 'failure'
from @my_table
having sum(case when status_code != 200 then 1 else 0 end) <= 5;
-- RESULT (1 row)
success failure
----------- -----------
1 2
没有结果:
insert into @my_table (status_code) values
(1), (1), (1), (1); --> +4 failures ==> 6 failures in total
select sum(case when status_code = 200 then 1 else 0 end) as 'success',
sum(case when status_code != 200 then 1 else 0 end) as 'failure'
from @my_table
having sum(case when status_code != 200 then 1 else 0 end) <= 5;
-- RESULT (0 rows)
推荐阅读
- github - 创建一个 Dev 分支并将代码从本地推送到 Dev
- sql - 明确区分 pg_stat_statements 中的类似查询?
- java - 如果同一个应用程序的两个实例订阅了一个主题,如何避免重复处理消息?
- azure - Azure Webjob 在 4 分钟后失败
- python - 选择库列
- c# - 如何忽略运算符重载
- c# - 通过示例了解六角端口和适配器的概念
- rabbitmq - 面临安装 RabbitMQ 管理控制台插件的问题
- sql - oracle查询的查询优化
- android - 无法解决:将 google-services 更新到 15.0.0 后 play-services-basement