1

以下是“列出拥有所有可用颜色项目的客户的查询。也就是说,对于每种可用颜色,客户拥有该颜色的一些项目。” 项目是客户购买的项目表

select cust#, cname
    from Customer
except
select C.cust#, C.cname
    from ( select D.cust#, A.colour
        from Customer D,
            Avail_Colours A
        except
        select I.cust#, I.colour
        from Item I
    ) as M,
    Customer C
where C.cust# = M.cust#;

如果我想将问题改写为:“列出拥有某种可用颜色的所有商品的客户”,即列出可用颜色以及客户拥有该颜色的所有商品的客户,该怎么办?

4

3 回答 3

0

(The following assumes that you are looking for a solution using EXCEPT.)

Take the cross product of all available items with all available customers and all available colours. Now take away from that set all the existing items, with their actual owners and colours. Apparently, if a customer has all items in some colour, the resulting set will lack the corresponding colour(s) for that customer. You can get the list of all such customers and their "full-set" colours if you take away this resulting set from the cross product of all customers and colours.

Translating the above into EXCEPT SQL, here's what you can get:

SELECT D.cust#,
       D.name,
       C.colour
FROM   Customer D,
       Avail_Colours C
EXCEPT
SELECT D.cust#,
       D.name,
       S.colour
FROM   (
        SELECT D.cust#,
               I.item#,
               C.colour
        FROM   Items I,
               Customer D,
               Avail_Colours C
        EXCEPT
        SELECT I.cust#,
               I.item#,
               I.colour
        FROM   Items I
       ) S
JOIN   Customer D
ON     D.cust# = S.cust#
;
于 2013-04-04T21:37:14.343 回答
0

以下版本假设颜色都可用:

select i.cust#, i.colour, COUNT(distinct i.item#) as numItems
from items i join
     (select i.cust# , COUNT(distinct i.item#) as numItems
      from items i
      group by i.cust#
     ) isum
     on isum.cust# = i.cust#
group by i.cust#, i.colour
having i.numItems = max(isum.numItems)

它返回所有商品的客户编号和颜色(如果有)。

要获得可用的颜色,您只需将以下where子句添加到子查询和外部查询:

where colour in (select colour from Avail_Colours)
于 2013-04-04T18:51:15.837 回答
0

我无权访问 DB2,因此无法对其进行测试。请认为这只是一个想法,而不是一个现成的解决方案。我使用标准 SQL。

SELECT c.cust#, MAX(c.cname), a.colour 
FROM Customer c 
JOIN Items i ON c.cust# = i.cust#
JOIN Avail_Colors a ON a.colour=i.colour
GROUP BY c.cust#, i.colour
HAVING COUNT(*)=(SELECT COUNT(*) FROM Item WHERE i.colour = a.colour) 
ORDER BY c.cust#
于 2013-04-04T18:41:35.170 回答