SQL:Group By ...有问题

时间:2018-04-17 18:29:50

标签: sql group-by

我试图绕过这个SQL查询,但我真的遇到了麻烦。

我有一个包含idaddress的表格(其中id只是一个小写的addresss"id-"前缀。我想得到所有的此列表中ID与地址匹配的元素,但地址 由列表中的2个元素共享。

例如:

答:id="id-abcde"address=aBcDe

B:id="id-zxwy"address=aBcDe

我想返回B,它在表中共享一个地址,其地址与其id不同。

我现在的查询是

select a.id, a.address 
from users as a 
where a.id != concat('id-', lower(a.address)) 
group by a.address, a.id 
having count(1) > 1

但是,这并没有返回正确的结果。

任何和所有帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

我想你想要:

select u.id, u.address 
from (select u.*, count(*) over (partition by address) as cnt
      from users u
     ) u
where u.id <> concat('id-', lower(u.address)) and cnt = 2;

如果您想要至少两个元素,请使用cnt > 1

答案 1 :(得分:0)

I don't think you need group by or having for this

try

select a.id, a.address from users a
where a.id != concat('id-',lower(a.address))

if you have multiple similar entries add distinct in the first line

select distinct a.id, a.address from users a

答案 2 :(得分:0)

尝试*不区分1,这样就可以测试多次出现的行而不只是一列。

select a.id, a.address from users as a where 
a.id != concat('id-', lower(a.address)) 
group by a.address, a.id 
having count(*) > 1