sql - Select Query with Conditional Check for group of records
问题描述
SELECT DISTINCT
t2.cmdb_id,
t1.src_sys_id,
t3.appl_nm,
t1.st_mgmnt_cd Status,
CASE
WHEN t1.st_mgmnt_cd != "PURGE"
THEN 'In-Progress'
ELSE 'In-Compliance'
END as Status,
t1.podium_delivery_date
FROM
table1 t1
JOIN
table2 t2
JOIN
table3 t3
WHERE
t1.src_sys_id = t2.ingstn_nm
AND t2.cmdb_id = t3.cmdb_id
The above query returns many rows where the status column is repeated. This is because on the original table, I have many states other than purge for the column st_mgmnt_cd
. But I need to do the check for all records under a cmdb_id
. Hence for a cmdb_id
, I need to have only one row in the results and status shown based on check.
How can I rewrite the query to do the check across the records of a cmdb_id
?
cmdb_id schema_name appl_nm status assessment_date
88 PAD PADCOD HOT 20180601
88 PAD PADCOD WARM 20180601
218 EED EEDCOD HOT 20180617
218 EED EEDCOD WARM 20180618
218 EED EEDCOD COLD 20180620
3106 ABC ABCOD HOT 20180601
3106 ABC ABCOD WARM 20180604
3106 ABC ABCOD EXPIRED 20180620
3106 ABC ABCOD PURGE 20180622
Results expected ==================
88 PAD PADCOD In-Progress 20180601
218 EED EEDCOD In-Progress 20180620
3106 ABC ABCOD In-Compliance 20180620
解决方案
将您的查询封装在 SELECT 中,并在内部查询中对 max(st_mgmntcd) 进行更改。
即 SELECT COL1, data FROM( SELECT COL1, MAX(REPETINGCOL) as data group by COL1) x
推荐阅读
- python - 匹配部分正确关键字的正则表达式
- crm - 将场从一个模块移动到另一个 Vtiger
- bash - 递归下用文件名的下划线替换空格
- oracle - 查询以搜索使用特定查找的所有包
- php - 代码在本地服务器上工作但在 Go-daddy 服务器上不起作用
- python - Python3:删除两个分隔字符之间的子字符串
- ios - 在 UITableViewController 的底部添加一个 ImageView
- node.js - 我可以在不使用/安装 node.js/npm 的情况下设置 Angular 6 吗?
- forms - 在 Google Apps 脚本 Web 应用程序表单中自动关闭
- python - 如何对使用 Flask 的 app.logger 的函数进行单元测试