简体   繁体   中英

Any way to group the result of a DISTINCT and get the COUNT of the rows grouped correctly?

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?

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM