英文:
How to find column A values are different but column B values are the same within the same pk
问题
首先,我为通过翻译提问而道歉。
我有一个Presto SQL的问题。
如下表所示,我想选择那些具有多个PK且Item1不同但Item2相同的情况。
当我进行自连接时,具有一个PK中有三个或更多项的项目无法输出。
(以下部分为原文,请自行查看)
英文:
First of all, I apologize for asking a question through a translator.
I have a presto SQL question.
As shown in the table below, I want to select cases where there are multiple PKs and Item1 is different but Item2 is the same.
When I self-joined, items with three or more items in one PK could not be output.
.
.
.
.
.
.
.
.
.
.
答案1
得分: 1
drop table if exists temp_test;
创建临时表 temp_test(pk smallint,item1 varchar(30),item2 varchar(30));
插入到 temp_test 中的值为
(1,'红色衬衫','绿色衬衫'),
(1,'蓝色衬衫','绿色衬衫'),
(2,'黄色帽子','黑色帽子'),
(3,'绿色汽车','蓝色汽车'),
(4,'紫色手帕','红色手帕'),
(5,'红色袜子','白色袜子'),
(5,'黄色袜子','白色袜子'),
(5,'绿色袜子','白色袜子'),
(6,'银色盘子','白金盘子'),
(6,'银色盘子','白金盘子');
使用
(
pk,
count(distinct item1) item1,
count(distinct item2) item2
)
从 temp_test 中选择堆栈
按 1 分组;
选择
a.pk,
a.item2
从
temp_test a
与堆栈内部连接(
a.pk = stacks.pk
和 stacks.item1 != stacks.item2
)
按 1,2 分组。
英文:
drop table if exists temp_test;
create temp table temp_test (pk smallint,item1 varchar(30),item2 varchar(30));
insert into temp_test values
(1,'red shirts','green shirts'),
(1,'blue shirts','green shirts'),
(2,'yellow cap','black cap'),
(3,'green car','blue car'),
(4,'purple handkerchief','red handkerchief'),
(5,'red socks','white socks'),
(5,'yellow socks','white socks'),
(5,'green socks','white socks'),
(6,'silver plate','platin plate'),
(6,'silver plate','platin plate')
;
with
stacks as (
select
pk,
count(distinct item1) item1,
count(distinct item2) item2
from
temp_test
group by 1
)
select
a.pk,
a.item2
from
temp_test a
inner join stacks on (
a.pk = stacks.pk
and stacks.item1 != stacks.item2
)
group by 1,2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论