Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

sql - How to count distinct records

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...