查找对所有艺术家感兴趣的任何客户的客户名称

时间:2016-06-10 15:03:14

标签: sql oracle

我正在寻找对所有艺术家感兴趣的客户的客户名称。我不知道如何使用sql获取它。这里需要帮助。

我有这些带有列的表。

Artist (ARTISTID,LASTNAME, FIRSTNAME)

Customer (CUSTOMERID, LASTNAME, FIRSTNAME)

CUSTOMER_ARTIST_INT (ARTISTID, CUSTOMERID)

4 个答案:

答案 0 :(得分:1)

您可以通过以下方式获取客户ID:

select customerid
from customer_artist_int cai
group by customerid
having count(*) = (select count(*) from artist);

然后,您可以使用joinin来获取其他客户信息。

答案 1 :(得分:0)

解决这些问题的一种巧妙方法就是颠倒它们 - 找到所有没有艺术家的客户,他们并不感兴趣。这听起来有点令人费解,但是当你把它转换成SQL时,它变得相当优雅:

SELECT *
FROM   customer c
WHERE  NOT EXISTS (SELECT *
                   FROM   artist a
                   JOIN   customer_artist_int cai ON a.artistid = cai.artistid
                   WHERE  cai.customerid = c.customerid)

答案 2 :(得分:0)

如果我说得好,这可能是一种方式

<强>设定:

create table Artist (ARTISTID,LASTNAME, FIRSTNAME) as
select '1', 'lastname_artist_1', 'first_name_artist_1' from dual union all
select '2', 'lastname_artist_2', 'first_name_artist_2' from dual union all
select '3', 'lastname_artist_3', 'first_name_artist_3' from dual 

create table Customer (CUSTOMERID, LASTNAME, FIRSTNAME) as
select '1', 'lastname_customer_1', 'first_name_customer_1' from dual union all
select '2', 'lastname_customer_2', 'first_name_customer_2' from dual union all
select '3', 'lastname_customer_3', 'first_name_customer_3' from dual

create table CUSTOMER_ARTIST_INT (ARTISTID, CUSTOMERID) as
select 1, 1 from dual union all
select 2, 1 from dual union all
select 3, 1 from dual union all
select 2, 2 from dual 

<强>查询:

SELECT CUSTOMERID,
         LASTNAME,
         FIRSTNAME,
         COUNT(DISTINCT artistid)
    FROM customer c INNER JOIN customer_artist_int USING (customerid)
GROUP BY CUSTOMERID,
         LASTNAME,
         FIRSTNAME
  HAVING COUNT(artistid) = (SELECT COUNT(1) FROM Artist)

在此计算每个顾客感兴趣的artstis数量,并检查它是否等于所有艺术家的数量。

答案 3 :(得分:0)

我不认为我的答案是最优雅的,但这是我的尝试..

SELECT c.FIRSTNAME, c.LASTNAME, c.CUSTOMERID
FROM DTOOHEY.CUSTOMER c, DTOOHEY.CUSTOMER_ARTIST_INT cai
WHERE c.CUSTOMERID = cai.CUSTOMERID 
AND c.CUSTOMERID IN 
(SELECT cai.CUSTOMERID
  FROM DTOOHEY.CUSTOMER_ARTIST_INT cai
  GROUP BY cai.CUSTOMERID
  HAVING COUNT (*) = (SELECT COUNT (*) FROM DTOOHEY.ARTIST)
)
GROUP BY c.FIRSTNAME, c.LASTNAME, c.CUSTOMERID;

根据我的有限知识,命令流程是:
1)我正在尝试获取客户ID,客户的名字和姓氏
2)我从2个表(cai和c)中得到它
3)尝试加入2个表来给我一个数据集
4)c.customerid将聚集在......
这就是魔术开始的地方!
5)选择customerID(单个CustomerID)
6)从这张表蔡
7)根据customerID对结果进行分组,这就是您需要的单个CustomerID值...
8)具有COUNT(*) - 具有customerID值的计数,与dtoohey.artist表中的艺术家数量相等。

主要逻辑是艺术家表中的艺术家数量(即11),存在于CUSTOMER_ARTIST_INT中的数量相同。因此,我们可以将计数结果从ARTIST表统计到CUSTOMER_ARTIST_INT表中。