简体   繁体   中英

SQL COUNT DISTINCT for each ID in MS Access

Say I had a table as follows:

id  category       app
------------------------
1   game           angry birds
1   game           happy dogs
2   productivity   calculator
3   health         fitness tracker
1   game           angry birds
2   game           snake

The table shows every app that the user opens over time. For example, pretend you wrote down each time you opened an app on your phone. Now repeat this for 100 people. All of that data is stored in one table, as above.

I am trying to figure out how to count how many distinct apps each person uses within a particular category. For example, for the 'game' category, I would expect:

id  num_apps
------------
1   2
2   1
3   0

I understand that one cannot use COUNT(DISTINCT ..) in MS-Access, and have seen other posts on how to achieve this - I haven't been able to apply it to this case though.

I have tried the following, which I believe gives me a non-distinct count of how each app anyone ever used in a particular category:

SELECT COUNT(*)
FROM
(SELECT DISTINCT id AS gamer_id
FROM UseList
WHERE category = 'game')
AS b, UseList AS ul
WHERE b.gamer_id = ul.id AND category = 'game'
GROUP BY b.gamer_id;

How could I apply to distinct search to this? I've thought of somehow looping through each gamer_id , but that doesn't seem too straightforward either. Thanks!

you could use

  select t.id, count(*)
  from (
  select distinct id, app
  from  UseList 
  where categorty ='game') t

  group by t.id 

I am not sure I understood, but can you try this?

SELECT A.ID, A.CATEGORY , COUNT(APP) AS NUM_APPS
FROM 
(SELECT A1.ID, A2.CATEGORY 
 FROM ( SELECT DISTINCT ID FROM TG1) A1
      CROSS JOIN (SELECT DISTINCT  CATEGORY FROM TG1) A2
) A
LEFT JOIN (SELECT DISTINCT ID, CATEGORY, APP 
          FROM TG1) B ON A.ID=B.ID AND A.CATEGORY=B.CATEGORY
GROUP BY A.ID, A.CATEGORY

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