聚合 SQL 中的行
Aggregating rows in SQL
我想 select 'Y' 或 'N' 超过 'U'- 只要有两行相同的 id。但是,当只有一行id时,我想保留'U'。谁能展示一种聚合以下内容的有效方法 table:
变成这样的东西:
我尝试了 MAX 函数,但它只保留按字母顺序排列的值,并且 'U' 恰好在 'Y' 和 'N' 的中间,因此 MAX 函数不起作用我打算。
很高兴听到你的想法。
您可以使用 window 函数:
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'
、return、'Y'
.
- 否则,如果有
'N'
return 'N'
.
- 否则,如果有
'U'
、return则'U'
。
假设您必须从 'U'、'Y' 和 'N' select 并且最多有 2 个存在,您可以简单地使用 Max 函数与 group by.
SELECT id, MAX(Ind)
FROM mytable
GROUP BY id
order by id
此查询适用于大多数数据库。
使用上面的方法要小心,虽然它简单而且小但是有很多限制。在投入生产之前对其进行彻底测试,并考虑所有测试用例。
我想 select 'Y' 或 'N' 超过 'U'- 只要有两行相同的 id。但是,当只有一行id时,我想保留'U'。谁能展示一种聚合以下内容的有效方法 table:
变成这样的东西:
我尝试了 MAX 函数,但它只保留按字母顺序排列的值,并且 'U' 恰好在 'Y' 和 'N' 的中间,因此 MAX 函数不起作用我打算。
很高兴听到你的想法。
您可以使用 window 函数:
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'
、return、'Y'
. - 否则,如果有
'N'
return'N'
. - 否则,如果有
'U'
、return则'U'
。
假设您必须从 'U'、'Y' 和 'N' select 并且最多有 2 个存在,您可以简单地使用 Max 函数与 group by.
SELECT id, MAX(Ind)
FROM mytable
GROUP BY id
order by id
此查询适用于大多数数据库。 使用上面的方法要小心,虽然它简单而且小但是有很多限制。在投入生产之前对其进行彻底测试,并考虑所有测试用例。