Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count distinct records

Tags:

sql

ms-access

Could anybody please help me on SQL command?

I have a table (tbl_sActivity) that have below data:

user_id | client_id | act_status |
1           |     7        |      cold     |
1           |     7        |    dealed   |
22         |     5        |      cold     |
1           |     6        |      cold     |
1           |     6        |     warm    |
1           |     6        |      hot       |
1           |     6        |    dealed   |
1           |     8        |     warm    |
1           |     8        |    dealed   |
21         |     4        |     warm    |
21         |     4        |    dealed   |

The out put should be

user_id | Count_C_id |
 1          |     3             |
 21        |     1             |
 22        |     1             |

I've searched from net and learnt that MS ACCESS cannot use COUNT(DISTINCT) function. So I'm stuck at this stage for days.

like image 647
Alxan Avatar asked Aug 15 '12 07:08

Alxan


People also ask

How do I count distinct records?

The COUNT DISTINCT function returns the number of unique values in the column or expression, as the following example shows. SELECT COUNT (DISTINCT item_num) FROM items; If the COUNT DISTINCT function encounters NULL values, it ignores them unless every value in the specified column is NULL.

How can I count distinct rows in SQL?

We can use SQL Count Function to return the number of rows in the specified condition. The syntax of the SQL COUNT function: COUNT ([ALL | DISTINCT] expression); By default, SQL Server Count Function uses All keyword.

Is count in SQL distinct?

COUNT(DISTINCT expression) evaluates expression for each row in a group, and returns the number of unique, nonnull values. For return values exceeding 2^31-1, COUNT returns an error. For these cases, use COUNT_BIG instead. COUNT is a deterministic function when used without the OVER and ORDER BY clauses.


1 Answers

Try this one. The "trick" is to have a subquery first to get all the distinct combinations of user and client IDs and then do the grouping per user:

SELECT
    user_id
  , COUNT(*) AS count_distinct_clients
FROM
    ( SELECT DISTINCT
          user_id, 
          client_id
      FROM tbl_sActivity
    ) AS tmp
GROUP BY
    user_id ;
like image 84
ypercubeᵀᴹ Avatar answered Oct 24 '22 13:10

ypercubeᵀᴹ