[英]Aggregating rows in SQL
您可以使用窗口函数:
select id, ind
from (
select t.*, row_number() over(
partition by id
order by case ind
when 'Y' then 1
when 'N' then 2
when 'U' then 3
else 4 -- is this possible?
end
) rn
from mytable t
) t
where rn = 1
或者,我们可以将字符串转换为数字,选择首选值,然后转换回原始字符串:
select id,
case min(
case ind
when 'Y' then 1
when 'N' then 2
when 'U' then 3
end
)
when 1 then 'Y'
when 2 then 'N'
when 3 then 'U'
else '??'
end as ind
from mytable
group by id
另一种方法是聚合:
select id,
coalesce(max(case when ind = 'Y' then ind end),
max(case when ind = 'N' then ind end),
max(case when ind = 'U' then ind end)
)
from t
group by id;
这只是运行逻辑:
'Y'
,则返回'Y'
。'N'
返回'N'
。'U'
,则返回'U'
。假设您必须从 'U'、'Y' 和 'N' 中进行选择,并且存在最多2 个,您可以简单地将Max函数与 group by 一起使用。
SELECT id, MAX(Ind)
FROM mytable
GROUP BY id
order by id
此查询适用于大多数数据库。 小心使用上面的,虽然它简单小,但它有很多限制。 在投入生产之前彻底测试它并考虑所有测试用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.