gpt4 book ai didi

sql同名但值不同

转载 作者:行者123 更新时间:2023-12-01 09:32:56 24 4
gpt4 key购买 nike

如何检索所有具有相同名称但具有不同值的行?比如我有这张表:

Name|Value|Description
Rob |Val1 |Text1
Alex|Val1 |Text2
Alan|Val2 |Text3
Alex|Val2 |Text4
Alex|Val2 |Text5
Alan|Val2 |Text6

我希望查询只返回多次出现但具有不同值的人。所以结果是:

Alex|Val1 |Text2 
Alex|Val2 |Text4
Alex|Val2 |Text5

编辑:我在初始表中添加了另一行。一些查询也将返回 Alan 作为结果的一部分。我不希望那样,因为显然它具有相同的值(value)。如何实现?

最佳答案

尝试将 joinsybqueryhave 一起使用:

  select p.Name,p.Value,p.Description
from persons P
join ( select Name,Value
from persons
group by Name,Value
having count(1)>1
) c on p.Name = c.Name
and p.Value = c.Value
order by p.Name;

exists子句中的相同subquery:

select p.Name,p.Value,p.Description
from persons P
where exists
( select Name,Value
from persons c
where p.Name = c.Name
group by Name,Value
having count(1)>1
)
order by p.Name

SQL Fiddle演示

更新问题的解决方案

select * 
from Persons c
where name in
(
select Name from(
select Name,Value
from persons
group by Name,Value) T

group by Name
having count(1)>1
)

SQL Fiddle演示

关于sql同名但值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13067447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com