0

I have a table which includes the columns 'buyer', 'seller' and 'buyer_spend'. Each purchase is shown as a separate row with the buyer name, the seller name and the amount that's been bought.

Is it possible to use a single query to show all the distinct buyers that have not purchased from a seller?

For example if I have 'Seller A', I want to find all of the distinct Buyers that have not purchased from Seller A. I'm having trouble because the following query return all transactions that were not for Seller A, which includes many Buyers that have indeed purchased from Seller A on another row.

SELECT DISTINCT buyer WHERE seller!='Seller A';

This is probably quite straightforward, but I'm struggling to get my head round it.

Many thanks in advance.

Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
sicr
  • 2,148
  • 5
  • 23
  • 27

5 Answers5

1
SELECT DISTINCT buyer FROM table WHERE buyer NOT IN 
    (SELECT DISTINCT buyer FROM table WHERE seller='Seller A')
Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
1
SELECT a.buyer FROM table a WHERE Left Join table as b
on a.id = b.id and a.seller='Seller A'
WHERE b.id is null
group by a.buyer
levi
  • 3,451
  • 6
  • 50
  • 86
  • can you explain a bit more extensively your answer? tnx – Daniele B May 29 '12 at 23:13
  • I make left join with the same table on id and a.seller='Seller A'. If the buyer has purchased smth, b.id will have some mean else it will be null, that last we need – levi May 30 '12 at 07:59
0

I guess you want something like this

select distinct buyer from purchasetable where buyer not in (select buyer from buyertable)

Although, I am a SQL Server developer, I think this will still apply.

Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
0

Here is an alternative approach that doesn't use a join:

select buyer
from (select buyer, max(case when seller = 'Seller A' then 1 else 0 end) as hasSellerA
      from t
      group by buyer
     ) t
where hasSellerA = 0

In my experience, an aggregation query often performs better than an anti-join (not-in joins are anti-joins).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0
SELECT buyer
FROM atable
GROUP BY buyer
HAVING COUNT(seller = 'Seller A' OR NULL) = 0
  /* or: SUM(seller = 'Seller'A') = 0 */
Andriy M
  • 76,112
  • 17
  • 94
  • 154