我将如何创建一个查询,为我提供购买次数相同的客户名称

时间:2018-06-25 18:12:44

标签: sql database db2 relational-database

哪些对顾客至少购买了一本书?

列出不同的客户对(按名称)。对于每对客户,请先显示具有较大CID的客户;将这两列命名为customera和customerb。

这是我尝试过的方法,但是我一直遇到错误。以及如何使用别名重命名列名?

select cusA.name, cusB.name
from yrb_customer cusA, yrb_customer cusA, yrb_purchase A, yrb_purchase B
where A.title=B.title
and A.cid<>B.cid;

假设输出如下:

CUSTOMERA            CUSTOMERB
-------------------- --------------------
Jackie Johassen      Al Bore
Margaret Mitchie     Al Bore
Phil Regis           Al Bore
Pretence Parker      Al Bore
Doris Daniels        Andy Aardverk
George Gush          Andy Aardverk
...

282 record(s) selected.


create table yrb_customer (
cid   smallint  not null,
name  varchar(20),
city  varchar(15),
constraint yrb_customer_pk
    primary key (cid));


create table yrb_purchase (
cid    smallint     not null,
club   varchar(15)  not null,
title  varchar(25)  not null,
year   smallint     not null,
when   timestamp    not null,
qnty   smallint     not null,...



insert into yrb_customer (cid, name, city) values
(1,'Tracy Turnip','Richmond'),
(2,'Qfwfq','Pluto'),
(3,'Fuzzy Fowles','Petersburg'),
(4,'Suzy Sedwick','Williamsburg'),...

insert into yrb_purchase (cid,club,title,year,when,qnty) values
(1,'Basic','Will Snoopy find Lucy?',1985,'2001-12-1-11.59.00',1),
(1,'Readers Digest','Flibber Gibber',2000,'2001-12-1-11.59.00',1),
(1,'Readers Digest','Yon-juu Hachi',1948,'1999-4-20-12.12.00',1),
(1,'W&M Club','Nothing but Steak',1991,'2001-12-1-11.59.00',1),

2 个答案:

答案 0 :(得分:0)

查询看起来有点不对劲。例如,购买未链接到客户表。也许尝试:

select cusA.name, cusB.name
from yrb_customer cusA, yrb_customer cusB, yrb_purchase A, yrb_purchase B
where cusA.cid=A.cid
and cusB.cid=B.cid
and A.title=B.title
and A.cid > B.cid;

您也可以使用JOIN来实现相同的行为。

答案 1 :(得分:0)

尝试下面提到的查询

Select cusA.name, cusB.name
from yrb_customer cusA, yrb_customer cusB, yrb_purchase A, yrb_purchase B
Where A.cid <> B.cid
and cusA.cid = A.cid
and cusB.cid = B.cid
and A.title = B.title;