简体   繁体   English

SQL选择不同但详尽的列

[英]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);
  1. You need distinct values of Col1 with a row-number. 您需要具有行号的Col1不同值。
  2. You need also distinct values of Col2 with a row-number. 您还需要带有行号的Col2不同值。
  3. Now you can set a FULL OUTER JOIN by using UNION ALL over those distinct values ON row-numbers. 现在,你可以设置一个FULL OUTER JOIN使用UNION ALL对这些不同的值ON行数量。

[ SQL Fiddle Demo ] [ SQL Fiddle Demo ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM