I have a simple table with 2 columns:
Col1 | Col2
-----+-----
1 | 3
1 | 4
2 | 3
2 | 4
... many more rows
I want to return this:
Col1 | Col2
-----+-----
1 | 3
2 | 4
I don't want this:
Col1 | Col2
-----+-----
1 | 3
2 | 3
because 3 is duplicated in Col2, nor this
Col1 | Col2
-----+-----
1 | 3
1 | 4
because 1 is duplicated in Col1, nor this
Col1 | Col2
-----+----
1 | 3
because now 4 is missing in Col2. In other words, I don't want duplicates, but I also don't want to omit any values in col2 (unless it occurs with a duplicate in Col1 - and vice versa). How can I use SQL to do what I want? Thanks.
its working as per your given sample data
select col1,
case
when col1 =1 and col2 in (3,4) Then 3
when col1 =2 and col2 in (3,4) Then 4
end as col2
from table1
group by col1
for more detail go here sql fiddle
I think you need a query like this:
SELECT Col1, Col2
FROM
(SELECT dt.*, @rownum1 := @rownum1 + 1 AS rn
FROM
(SELECT Col1
FROM t
GROUP BY Col1) dt,
(SELECT @rownum1 := 0) r) t1
LEFT OUTER JOIN
(SELECT dt.*, @rownum2 := @rownum2 + 1 AS rn
FROM
(SELECT Col2
FROM t
GROUP BY Col2) dt,
(SELECT @rownum2 := 0) r) t2
ON t1.rn = t2.rn
UNION ALL
SELECT Col1, Col2
FROM
(SELECT dt.*, @rownum3 := @rownum3 + 1 AS rn
FROM
(SELECT Col2
FROM t
GROUP BY Col2) dt,
(SELECT @rownum3 := 0) r) t1
LEFT OUTER JOIN
(SELECT dt.*, @rownum4 := @rownum4 + 1 AS rn
FROM
(SELECT Col1
FROM t
GROUP BY Col1) dt,
(SELECT @rownum4 := 0) r) t2
WHERE (t2.Col1 IS NULL);
Col1
with a row-number. Col2
with a row-number. FULL OUTER JOIN
by using UNION ALL
over those distinct values ON
row-numbers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.