※ 引述《Falconeye (未识绮罗香)》之铭言:
: 两个字段如下:
: customer_id product_code
: 1 VF081
: 1 VF082
: 2 VF081
: 2 VF082
: 3 VF081
: 4 VF081
: 4 VF081
: 请教,要如何算出同时有VF081跟VF082的customer数量?
: 即id=1,2是符合条件的,答案为2笔
分别找出有订VF081与VF082的客户,然后取两者的交集。
举例来说:
create table test0314 (customer_id int, product_code varchar(10))
go
insert into test0314 values (1,'VF081')
insert into test0314 values (1,'VF082')
insert into test0314 values (2,'VF081')
insert into test0314 values (2,'VF082')
insert into test0314 values (3,'VF081')
insert into test0314 values (4,'VF081')
insert into test0314 values (4,'VF081')
go
select count(*) from
(select distinct customer_id from test0314 where product_code = 'VF081') as A
inner join
(select distinct customer_id from test0314 where product_code = 'VF082') as B
on A.customer_id = B.customer_id
go