[英]SQL select distinct but exhaustive columns
I have a simple table with 2 columns: 我有一个包含2列的简单表:
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 因为在Col2中3是重复的,也不是
Col1 | Col2
-----+-----
1 | 3
1 | 4
because 1 is duplicated in Col1, nor this 因为1在Col1中重复,所以也不是
Col1 | Col2
-----+----
1 | 3
because now 4 is missing in Col2. 因为现在Col2中缺少4。 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).
换句话说,我不希望重复,但是我也不想忽略col2中的任何值(除非Col1中出现重复的情况,反之亦然)。 How can I use SQL to do what I want?
如何使用SQL来做我想做的事? 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. Col1
不同值。 Col2
with a row-number. Col2
不同值。 FULL OUTER JOIN
by using UNION ALL
over those distinct values ON
row-numbers. FULL OUTER JOIN
使用UNION ALL
对这些不同的值ON
行数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.