Postgres 比较来自 3 个不同表的相同行、计数和匹配

Postgres comparison same rows,count and match from 3 defferent tables

我有3张桌子

CREATE TABLE product (
        productid int,
        name varchar(80),
        safetystocklevel int,
        reorderpoint int,
        standardcost int,
        listprice numeric,
        productcategoryid numeric
        );

CREATE TABLE salesorderdetail (
        salesorderid int,
        salesorderdetailid int,
        orderqty int,
        productid int,
        unitprice numeric,
        unitpricediscount numeric,
        linetotal numeric
        );

CREATE TABLE salesorderheader (
        salesorderid int,
        orderdate date,
        duedate date,
        shipdate date,
        onlineorderflag int,
        customerid int,
        creditcardid int,
        subtotal numeric,
        taxamt  numeric,
        freight numeric,
        totaldue numeric
        );

我想知道下订单的客户 包含至少 3 个不同类别的产品

我想我应该这样做:

SELECT saleorderid,productid FROM salesorderdetail WHERE lag(productid)!= productid AND lead(productid)!= productid AND lag(productid)!=lead(productid))

INTERSECT

(SELECT productid,productcategoryid FROM product WHERE lag(productcategoryid)!=productcategoryid AND lead(productcategoryid)!=productcategoryid AND lead(productcategoryid)!=lag(productcategoryid))

应该这样做:

select distinct sh.customerid
from salesorderdetail sd
  join product p on p.productid = sd.productid
  join salesorderheader sh on sd.salesorderid = sh.salesorderid
group by sh.customerid, sh.salesorderid
having count(distinct p.productcategoryid) >= 3