显示列具有多个唯一值的记录

问题描述

我正在尝试建立一个查询,以显示第1列在第2列中具有多个唯一值的数据,并显示两条记录。例如:

COL1        COL2
----------------
Andy       White
Andy       Brown
Andy       Brown
Andy       Brown
Jess       Green
Jess       Green
Jess       Green

您可以看到Andy在COL2中具有多个唯一值 我想同时显示它们,最好也显示其余的列(选择*)

COL1       COL2       COL3       COL4
-------------------------------------
Andy      White       data       data
Andy      Brown       data       data

我不需要显示Jess的值,因为COL2中的所有值都相同。

我已经尝试找到SQL查询,但不幸的是,没有匹配的查询。

解决方法

如果只需要名称列表:

select distinct col1,col2
from (select col1,col2,count(distinct col2) over (partition by col1) cnt
      from t
     ) t
where cnt >= 2;

或者:

select distinct col1,col2
from t
where exists (select 1 from t t2 where t2.col1 = t.col1 and t2.col2 <> t.col2);

您可以添加:

select distinct col1,'data' as col3,'data' as col4

但这似乎并不是特别有用。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...