1

How do I create a SQL query that shows people who bought product A and who bought product B without using a subquery. Right now I am trying Where Product IN ('A' , 'B' ), without count distinct because I also need that information. Any ideas? Right now I am getting any A's and any B's. I want it to look like

JIM 03/20/2014 Product A
JIM 03/20/2014 Product B

And exclude anyone who doesn't purchase both. It currently looks like

SELECT First, Last, Date, Product
From TABLE1
Where (Date = @Today) AND (Product IN ('A' and 'B'))

(Also A and B are the only options in the product table)

ColorfulWind
  • 77
  • 1
  • 12

1 Answers1

2

Use group and having with a condition that requires both products to have been purchased:

SELECT First, Last, Date
From TABLE1
Where Date = @Today
AND Product IN ('A', 'B')
GROUP BY First, Last, Date
HAVING COUNT(DISTINCT Product) = 2

The key is adding DISTINCT to the COUNT(), which changes the result from the simple number of transactions to the number of different products purchased.

Bohemian
  • 412,405
  • 93
  • 575
  • 722