SQL使用case when查询每个name对应最新记录返回多行问题求解
问题原因
你原有SQL的问题是仅做了行转列的映射逻辑,没有做聚合操作,所以会返回所有符合id = '6326323'条件的行,某行对应列值为空是因为该行的name不匹配对应case的判断条件。
解决方案
方案1:直接用聚合函数(最简单,适配绝大多数SQL数据库)
用MAX聚合函数提取每个name对应的最新created_on,MAX会自动忽略NULL值,聚合后天然返回单行结果:
select MAX(case when name = 's1' then created_on end) as serv1, MAX(case when name = 's2' then created_on end) as serv2 from table tsl where id ='6326323';
方案2:窗口函数(扩展性更强)
如果后续需要同时获取最新记录对应的ref_id等其他字段,推荐用窗口函数先给每个name的记录按时间倒序排名,取排名第一的最新记录再做行转列:
select MAX(case when name = 's1' then created_on end) as serv1, MAX(case when name = 's2' then created_on end) as serv2 from ( select name, created_on, ROW_NUMBER() OVER (PARTITION BY name ORDER BY created_on DESC) as rn from table tsl where id = '6326323' ) t where rn = 1;
可选简化写法(适配支持FILTER语法的数据库,如PostgreSQL、MySQL 8.0+)
select MAX(created_on) FILTER (WHERE name = 's1') as serv1, MAX(created_on) FILTER (WHERE name = 's2') as serv2 from table tsl where id = '6326323';
内容的提问来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

