简体   繁体   English

如何在MS-Access中计算三个不同的不同值并在ID上分组?

[英]How do I count three different distinct values and group on an ID in MS-Access?

So I know MS-Access does not allow SELECT COUNT(DISTINCT....) FROM ... , but I am trying to find a more viable alternative to the usual standard of 所以我知道MS-Access不允许SELECT COUNT(DISTINCT....) FROM ... ,但是我正在尝试找到一种更可行的替代常规标准的方法。

SELECT COUNT(*) FROM (SELECT DISTINCT Name FROM table1)

My problem is I am trying to do three separate Count functions and group them on ID. 我的问题是我试图做三个单独的Count函数并将它们按ID分组。 If I use the method above, it is giving me the total unique value count for the whole table instead of the total count for only the value of ID. 如果使用上述方法,它将为我提供整个表的总唯一值计数,而不是仅给ID值的总计数。 I tried doing 我试着做

(SELECT COUNT(*) FROM (SELECT DISTINCT Name FROM table1 as T2
WHERE T2.ColumnA = T1.ColumnA)) As MyVal
FROM table1 as T1

but it tells me I need to specify a value for T1.ColumnA. 但是它告诉我我需要为T1.ColumnA指定一个值。

The SQL query I am trying to accomplish is this: 我要完成的SQL查询是这样的:

SELECT ID
COUNT(DISTINCT ColumnA) as CA,
COUNT(DISTINCT ColumnB) as CB,
COUNT(DISTINCT ColumnC) as CC
FROM table1
GROUP BY ID

Any ideas? 有任何想法吗?

You can use subqueries. 您可以使用子查询。 Assuming you have a table where each id occurs once: 假设您有一个表,每个ID都出现一次:

select (select count(*)
        from (select columnA
              from table1 t1
              where t1.id = t.id
              group by columnA
             ) as a
       ) as num_a,
       (select count(*)
        from (select columnB
              from table1 t1
              where t1.id = t.id
              group by columnB
             ) as b
       ) as num_b,
       (select count(*)
        from (select columnC
              from table1 t1
              where t1.id = t.id
              group by columnC
             ) as c
       ) as num_c
from <table with ids> as t;

I'm not sure if you'll think this is "viable". 我不确定您是否认为这是“可行的”。

EDIT: 编辑:

This makes it even more complicated . 这使其更加复杂。 . . it suggests that MS Access doesn't support correlation clauses more than one level deep (might you consider switching to another database?). 这表明MS Access不支持超过一个级别的关联子句(您是否考虑切换到另一个数据库?)。

In any case, the brute force way: 无论如何,蛮力方式:

select a.id, a.numA, b.numB, c.numC
from ((select id, count(*) as numA
       from (select id, columnA
             from table1 t1
             group by id, columnA
            ) as a
      ) as a inner join
      (select id, count(*) as numB
       from (select id, columnB
             from table1 t1
             group by id, columnB
            ) as b
      ) as b
      on a.id = b.id
     ) inner join
     (select id, count(*) as numC
      from (select id, columnC
            from table1 t1
            group by id, columnC
           ) as c
     ) c
     on c.id = a.id;

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

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