簡體   English   中英

SQL-跨列比較屬性

[英]SQL - comparing attributes across columns

我有下表

customers(custid, name)
orders(orderid, custid)
itemsordered(itemid, orderid)
items(itemid, description)

我的目標是讓每對都訂購了具有相同描述的商品的客戶,檢索兩個客戶的姓名。 消除重復,不要將客戶與自己配對,並且每對僅包含一次。 對於每對,按字母順序返回該對中的名稱。

我了解我需要引用兩個custid,並將它們的每個描述相互比較,例如:

select nameA
from customers nameA
join orders using (custid)
join itemsordered using (orderid)
join item using (itemid)
where (select nameB
from customers
from customers nameA
join orders using (custid)
join itemsordered using (orderid)
join item using (itemid)
where descriptionA = descriptionB

etc.

但不確定如何進行。 這是正確的答案:

Christina|Janine
Christina|Max
Christina|Teddy
Christina|David
Christina|Rachel
Rachel|Teddy
David|Janine
David|Rachel
David|Teddy
Janine|Rachel
Janine|Teddy
Janine|Max
Max|Teddy

我需要一些新的例子。 我的大部分猜測都包含以下子查詢:

select attribute from table
join anotherTable using (somekey)
where table in (select anotherAttribute 
from anotherTable
where....etc.

任何建議或方向將不勝感激。

更新:名稱是唯一的。

WITH t AS (
    SELECT DISTINCT c.name, i.description  -- collapse dupes per name
    FROM   customers    c
    JOIN   orders         USING (custid)
    JOIN   itemsordered   USING (orderid)
    JOIN   items        i USING (itemid)
    )
SELECT DISTINCT t.name, t1.name
FROM   t
JOIN   t t1 USING (description)
WHERE  t.name < t1.name    -- rules out self-joins and duplicate pairs
ORDER  BY 1, 2;

這與@Clodoaldo發布的內容類似,但有一些重要區別。

  • 假設唯一的名稱。 否則結果將毫無意義。 簡單的外部SELECT
    如果名稱不是唯一的,則需要(另外)輸出custid

  • 根據問題匹配description

  • 立即折疊每個客戶的重復描述。 只有很少的騙子,這將無濟於事。 數量多一些,可以提高性能。

with s as (
    select *
    from
        customers
        inner join
        orders using (custid)
        inner join
        itemsordered using (orderid)
        inner join
        items using (itemid)
)
select distinct
    least(s1.name, s2.name),
    greatest(s1.name, s2.name)
from
    s s1
    inner join
    s s2 on
        s1.description = s2.description
        and
        s1.custid < s2.custid
order by 1, 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM