如何找到在相同的主键内,列A的值不同但列B的值相同。

huangapple go评论53阅读模式
英文:

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.

enter image description here

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

huangapple
  • 本文由 发表于 2023年6月19日 16:06:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定