我必须选择不同的月份ID,以下查询返回重复的值。如何解决这个问题?
SELECT DISTINCT m1.ID as C1, m2.ID as C2
FROM Mois m1, Mois m2
WHERE m1.ID IN('1','4','9')
AND m2.ID IN('2','5','10')
这就是我想要的:
C1 | C2
1 | 2
4 | 5
9 | 10
答案 0 :(得分:1)
SELECT MIN(C1),MIN(C2) FROM
(
SELECT DISTINCT m1.ID as C1, m2.ID as C2,
ROW_NUMBER() OVER (PARTITION BY m2.ID ORDER BY (SELECT 0)) AS ROWNUM
FROM Mois m1
INNER JOIN Mois m2
ON m1.ID IN (1, 4, 9) AND
m2.ID IN (2, 5, 10) AND
m1.ID < m2.ID
) AS T1
GROUP BY ROWNUM
OR
SELECT C1,C2 from
(SELECT DISTINCT m1.ID AS C1,
Row_number() over (Order by (SELECT 0)) AS RN
FROM Mois m1
WHERE m1.ID IN('1','4','9')) AS T1
INNER JOIN
(SELECT DISTINCT m2.ID AS C2,
Row_number() over (Order by (SELECT 0)) AS RN
FROM Mois m2
WHERE m2.ID IN('2','5','10')) AS T2
ON T1.RN=T2.RN
输出
C1 C2
1 2
4 5
9 10
演示
答案 1 :(得分:1)
尝试此选项:
WITH cte1 AS (
SELECT DISTINCT m1.ID as C1, m2.ID as C2
FROM Mois m1
INNER JOIN Mois m2
ON m1.ID IN (1, 4, 9) AND
m2.ID IN (2, 5, 10) AND
m1.ID < m2.ID
),
cte2 AS (
SELECT C1, C2, ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY C2) rn
FROM cte1
)
SELECT C1, C2
FROM cte2
WHERE rn = 1
ORDER BY C1;
C1 C2
1 1 2
2 4 5
3 9 10