sql - 使用 CASE 时按列值分组
问题描述
select C.name as Name,
C.id as ID,
(CASE WHEN CA.type_id = 231 and c.id = CA.id then CA.value end ) as PGroup,
(CASE WHEN CA.type_id IN ( 32, 38, 40, 52 ) and c.id = CA.id then CA.value end )as Facilty,
TC.cname as firmName
from tbCases C
join tbCompanies TC on TC.company_id = C.lawfirm_id
join tbAttributes CA on C.case_id = CA.case_id
where C.client_id = 9026 and c.id = 812429
我的结果
Name ID PGroup Facilty firmName
WA-SPOK 812429 NULL SPOKANE CUMMINGS LLP
WA-SPOK 812429 NULL VLLEY HSP CUMMINGS LLP
WA-SPOK 812429 Operations NULL CUMMINGS LLP
我正在尝试获得类似的结果
Name ID PGroup Facilty firmName
WA-SPOK 812429 Operations SPOKANE CUMMINGS LLP
WA-SPOK 812429 Operations VLLEY HSP CUMMINGS LLP
我试过分组。如何实现这一点。
解决方案
这将受益于一些示例数据,基于这样的查询可以工作
with pgroup_cte([Name], ID, firmName, PGroup) as (
select top(1) C.[name], C.id, TC.cname,
(CASE WHEN CA.type_id = 231 and c.id = CA.id then CA.value end)
from tbCases C
join tbCompanies TC on TC.company_id = C.lawfirm_id
join tbAttributes CA on C.case_id = CA.case_id
where C.client_id = 9026
and c.id = 812429
and (CASE WHEN CA.type_id IN ( 32, 38, 40, 52 ) and c.id = CA.id
then CA.value end) is null)
select C.[name],
C.id,
pc.PGroup,
(CASE WHEN CA.type_id IN ( 32, 38, 40, 52 ) and c.id = CA.id then CA.value end) as Facilty,
TC.cname as firmName
from tbCases C
join tbCompanies TC on TC.company_id = C.lawfirm_id
join tbAttributes CA on C.case_id = CA.case_id
join pgroup_cte pc on c.[Name]=pc.[Name]
and c.id=pc.id
and tc.cname=pc.firmName
where C.client_id = 9026
and c.id = 812429
and (CASE WHEN CA.type_id IN ( 32, 38, 40, 52 ) and c.id = CA.id
then CA.value end) is not null;
推荐阅读
- c# - 在 http 中加载 url 时 Application_BeginRequest() 没有被触发
- vue.js - 组件动态导入失败
- ocr - Tesseract 是否可以显示字符的识别百分比?
- javascript - 在 QT Qml 中动态创建导致冻结且无响应的对象
- google-chrome - 清除 CORS 的浏览器缓存
- python - Python:使用不完整或没有内部网格的 cv2 检测表
- css - 使列占用缺失列的空间
- netlogo - Netlogo中病毒传播过程中将“自我”从易感染者更改为错误
- php - 自 WooCommerce 3+ 起以编程方式创建优惠券
- git - 是否可以悄悄地对 git 存储库进行更改?