sql - 合并同一张表中的两行并计算总数
问题描述
我有一个有两列的表,如下所示:
total | measure
________________
1 | private vehicle use
4 | private car use
7 | other
我想将前两行合并为一行,将合并行的度量(strEUCategory)重命名为“私人车辆使用”。我也想合并总数。我已经研究了 CASE 和 PIVOT,但在计算总数的同时无法让它工作。
这是我的查询。
SELECT count(m.strEUCategory) as total , m.strEUCategory as measure
from laqm2_AQAP_measures m
where m.strYearIntroduced <=2020 and m.strCompletionYear >=2020
group by m.strEUCategory
order by m.strEUCategory
解决方案
我认为你想要一个case
表达式和聚合:
select
case when strEUCategory = 'private car use' then 'private vehicule use' else strEUCategory end as measure,
count(*) cnt
from laqm2_AQAP_measures
where strYearIntroduced <= 2020 and strCompletionYear >= 2020
group by measure
order by measure
如果您想对新类别名称进行更多控制,则:
select
case when strEUCategory in ('private car use', 'private vehicle use')
then 'Private Vehicule Use'
else strEUCategory
end as measure,
count(*) cnt
from laqm2_AQAP_measures
where strYearIntroduced <= 2020 and strCompletionYear >= 2020
group by measure
order by measure
推荐阅读
- outlook - 使用非 o365 配置文件(连接到自定义服务器)的 MS Teams 安排会议返回错误 FailedToGetCalendarFromOutlook
- node.js - 如何在我的后端通过 Facebook 验证社交登录?
- java - 使用管理 SDK 连接到 Firebase 实时数据库不会触发初始 onDataChange 回调
- ansible - Ansible 为所有人和组运行一个角色
- c# - SqlBulkCopy 抛出“由于对象的当前状态,操作无效”
- elasticsearch - 如果我从不清理 Elasticsearch 任务会怎样?
- c# - 如何保护 MVC 返回文件方法免受 XSS 攻击
- azure - Azure EventGrid 触发器 - Webhook
- javascript - TensorflowJs - 用因子重新缩放图像
- arcore - 在运行时更新会话配置