我有下表
id | cId
---------------
1 | 1
2 | 1
3 | 2
4 | 2
我需要查询帮助,返回以下结果
id1 | id2 | cId
----------------------
1 | 2 | 1
3 | 4 | 2
SELECT s1.id firstC, s2.id secondC
FROM SingleTable s1 inner join SingleTable s2 on s1.cId = s2.cId
但我得到重复。我想要没有重复的gte结果。
我的结果:
id1 | id2 | cId
---------------
1 | 1 | 1
2 | 1 | 1
1 | 2 | 1
2 | 2 | 1
3 | 3 | 2
4 | 3 | 2
3 | 4 | 2
4 | 4 | 2
请帮忙。
答案 0 :(得分:1)
您可以按cId
分组,然后为每id
cId
SELECT cId,
min(id) as id1,
max(id) as id2
FROM SingleTable
GROUP BY cId
答案 1 :(得分:1)
删除带有额外条件(s1.id = s2.id
)的重复项(s1.id < s2.id
):
SELECT s1.id firstC, s2.id secondC
FROM SingleTable s1 INNER JOIN SingleTable s2
ON (s1.cId = s2.cId AND s1.id < s2.id)