简体   繁体   中英

Select COUNT of column and GROUP BY

Here I am with a problem I can't solve myself.

My problem is:

I need to SELECT the count of a column, but I also need to GROUP BY on that same column. What I've tried so far is not returning as I expected.

Here is what I tried:

'SELECT COUNT(user_id) AS total_donors
    FROM ' . DONATION_SECURITY_TABLE .
    " WHERE payment_status = 'Completed' 
    GROUP BY user_id"

This is how my table looks like:

id    user_id    payment_status
1     20         Completed
2     33         Completed
3     44         Completed
4     20         Pending
5     33         Pending
6     44         Completed
7     20         Completed

As you see, a single user_id can be Pending or Completed more than once, but I want my query to return 3 (based on the table example above).

So, I want my query to COUNT GROUPED user_ids if payment status is completed.

Ideas?

You can use the DISTINCT keyword to select the unique User ID's like so

"SELECT COUNT(DISTINCT user_id) AS total_donors
FROM " . DONATION_SECURITY_TABLE .
" WHERE payment_status = 'Completed' 

sounds like a distinct count is what you need. throw away the group by and try this:

SELECT
  COUNT(DISTINCT user_id) AS total_donors
FROM
  mytable
WHERE
  payment_status = 'Completed'

For a result of 3, replace your Count(user_id) with Count(distinct user_id) and remove the group by.

That gives you the count of unique user_ids with a payment status of completed.

since you are only interested on the count of user_ID , you don't need to use GROUP BY clause

SELECT COUNT(DISTINCT user_ID)
FROM tableName
WHERE payment_status = 'completed'

when you try to add GROUP BY clause. the result is very different from what you are expecting.

Use this:

SELECT COUNT(DISTINCT `user_id`) as `Total` FROM `Donation_Table`
WHERE `payment_status` = 'Completed'

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