如何统计三个不同的不同值并对MS-Access中的ID进行分组?

时间:2016-09-13 21:19:08

标签: sql ms-access count distinct

所以我知道MS-Access不允许SELECT COUNT(DISTINCT....) FROM ...,但我试图找到一种比通常标准更可行的替代方案

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

我的问题是我正在尝试执行三个单独的Count函数并将它们分组到ID上。如果我使用上面的方法,它会给我整个表的总唯一值计数,而不是仅给出ID值的总计数。我试着做了

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

但它告诉我需要为T1.ColumnA指定一个值。

我想要完成的SQL查询是:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您可以使用子查询。假设你有一个表,其中每个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;

我不确定你是否认为这是“可行的”。

编辑:

这使它变得更加复杂。 。 。它表明MS Access不支持超过一级深度的相关子句(您可能考虑切换到另一个数据库吗?)。

无论如何,蛮力方式:

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;