[英]How do I count three different distinct values and group on an ID in MS-Access?
所以我知道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
有任何想法吗?
您可以使用子查询。 假设您有一个表,每个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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.