【问题标题】:How do I count three different distinct values and group on an ID in MS-Access?如何在 MS-Access 中计算一个 ID 上的三个不同的不同值和组?
【发布时间】:2017-01-21 14:13:52
【问题描述】:

所以我知道 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

有什么想法吗?

【问题讨论】:

  • (SELECT COUNT(*) FROM (SELECT DISTINCT Name FROM table1 as T2 WHERE T2.ColumnA = T1.ColumnA)) As MyVal FROM table1 as T1 通常不是有效的语法。不只是访问
  • 我不知道你为什么说它无效。它在下面的答案中被引用...
  • 它以(开头
  • 我明白你在说什么。这是查询中第三行的摘录,因此在它之前没有SELECT 或其他字段。对此造成的困惑,我深表歉意。
  • 哦哦,明白了。我错过了

标签: sql ms-access count distinct


【解决方案1】:

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

【讨论】:

  • 这不起作用。它询问我要指定什么作为 t.ID 的参数值,这与我之前遇到的问题相同。
猜你喜欢
  • 1970-01-01
  • 2010-11-27
  • 2022-08-15
  • 1970-01-01
  • 2014-10-13
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多