sql-server - SQL Server Count with case when
问题描述
我正在使用以下查询将技能值放入相应的类别中。
select distinct
case
when skilldescript like 'cspace%' then 'CSPACE'
when skilldescript like 'gen%' then 'GENERAL'
when skilldescript like 'rope%' then 'ROPE'
when skilldescript like 'sct%' then 'SCT'
when skilldescript like 'trench%' then 'TRENCH'
end as Skill_Category
from skillTable
查询给了我以下结果:
Skill_Category
--------------
CSPACE
GENERAL
ROPE
SCT
TRENCH
我现在想要完成的是让查询返回每个类别下有多少不同的技能集。所以结果应该是:
Skill_Category Count
----------------------
CSPACE 11
GENERAL 5
ROPE 20
SCT 10
TRENCH 3
我尝试使用 count() 或 sum(),但它们只选择单个行数。
解决方案
您必须按 CASE 表达式和计数进行分组:
select
case
when skilldescript like 'cspace%' then 'CSPACE'
when skilldescript like 'gen%' then 'GENERAL'
when skilldescript like 'rope%' then 'ROPE'
when skilldescript like 'sct%' then 'SCT'
when skilldescript like 'trench%' then 'TRENCH'
end as Skill_Category,
count(*) [Count]
from skillTable
group by case
when skilldescript like 'cspace%' then 'CSPACE'
when skilldescript like 'gen%' then 'GENERAL'
when skilldescript like 'rope%' then 'ROPE'
when skilldescript like 'sct%' then 'SCT'
when skilldescript like 'trench%' then 'TRENCH'
end
或者:
select Skill_Category, count(*) [Count]
from (
select
case
when skilldescript like 'cspace%' then 'CSPACE'
when skilldescript like 'gen%' then 'GENERAL'
when skilldescript like 'rope%' then 'ROPE'
when skilldescript like 'sct%' then 'SCT'
when skilldescript like 'trench%' then 'TRENCH'
end as Skill_Category,
count(*) [Count]
from skillTable
) t
group by Skill_Category
推荐阅读
- java - 使用 Mockito 的最佳实践
- python - numpy 加法是如何工作的?
- python - “open()”在大型 for 循环中失败
- php - 我们如何避免冗余代码行
- json - 如何解码 json 数据 Go
- xml - Sitecore XSL:通过路径或id选择项目,获取孩子,获取孩子的Droplink项目
- azure - 如何在生产中将调试级别日志消息输出到 Application Insights
- three.js - 使用three.js在两个管几何之间绘制平面
- android - 将google cloud sql连接到android studio项目
- javascript - axios 随机请求数