Reputation: 20049
I have this query:
SELECT DISTINCT w.buyer_id, u.username, a.cb_id
FROM winners AS w
INNER JOIN auctions AS a ON w.auction_id=a.auction_id AND a.cb_id > 0 AND a.category_id=1922
INNER JOIN users AS u ON w.buyer_id=u.user_id
So basically I am trying to find out how many unique entries each w.buyer_id
has been involved in with regards to a.cb_id
.
So to do that I ran the above query and I get a row by row result, which is good as it shows all the unique values; so I can see that user A has 14 rows (14 unique CB ID's they are involved in) and user B may have 5 rows.
So I want to make it so I can get a record set with an output of:
w.buyer_id,u.username,count
I tried the below:
SELECT DISTINCT w.buyer_id, u.username, a.cb_id, COUNT(*) AS unique_spots
FROM winners AS w
INNER JOIN auctions AS a ON w.auction_id=a.auction_id AND a.cb_id > 0 AND a.category_id=1922
INNER JOIN users AS u ON w.buyer_id=u.user_id
GROUP BY w.buyer_id
LIMIT 5000;
...but it returns the COUNT
as if I didn't even apply a DISTINCT
to the record set.
What am I doing wrong here?
Upvotes: 1
Views: 52
Reputation: 1
Have you tried this:
SELECT w.buyer_id, u.username, a.cb_id, COUNT(*) AS unique_spots
FROM winners AS w
INNER JOIN auctions AS a ON w.auction_id=a.auction_id AND a.cb_id > 0 AND a.category_id=1922
INNER JOIN users AS u ON w.buyer_id=u.user_id
GROUP BY w.buyer_id, u.username, a.cb_id
LIMIT 5000;
Upvotes: 0
Reputation: 1270493
How about just writing a query to do what you want directly?
SELECT w.buyer_id, COUNT(DISTINCT a.cb_id)
FROM winners w INNER JOIN
auctions a
ON w.auction_id = a.auction_id AND a.cb_id > 0 AND
a.category_id = 1922 INNER JOIN
users u ON w.buyer_id = u.user_id
GROUP BY w.buyer_id;
The join to users
seems superfluous:
SELECT w.buyer_id, COUNT(DISTINCT a.cb_id)
FROM winners w INNER JOIN
auctions a
ON w.auction_id = a.auction_id AND a.cb_id > 0 AND
a.category_id = 1922
GROUP BY w.buyer_id;
Upvotes: 2