简体   繁体   English

MS Access中每个ID的SQL COUNT DISTINCT

[英]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. 现在,对100个人重复此操作。 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. 我知道一个人不能在MS-Access中使用COUNT(DISTINCT ..),并且看过其他有关如何实现此目的的文章-尽管我无法将其应用于这种情况。

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. 我想到过以某种方式遍历每个gamer_id ,但这似乎也不太简单。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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