我对SQL和Ms Access数据库很陌生。
已经在线搜索了一些帖子,但仍然对DISTINCT COUNT
函数感到困惑。
是否可以通过以下简单方法完成以下操作而无需创建多个查询或VBA代码(由于性能问题)?或者可以使用子查询,如果可以,请问如何完成? 请真正感谢您的建议。
非常感谢和欢呼 贝利
表格:材料
结果如下:
答案 0 :(得分:1)
MS Access不支持COUNT(DISTINCT)
,所以这很棘手。一种方法使用子查询。我认为这会起作用:
select c.col0,
(select count(*)
from (select distinct m2.col1
from material as m2
where m2.col0 = c.col0
) as m2
) as dcol1,
(select count(*)
from (select distinct m2.col2
from material as m2
where m2.col0 = c.col0
) as m2
) as dcol2,
(select count(*)
from (select distinct m2.col3
from material as m2
where m2.col0 = c.col0
) as m2
) as dcol3
from (select distinct col0 from material) as c;
我不确定100%MS Access是否支持两个级别的关联子句。如果没有,您可以这样写:
select c.col0,
(select count(*)
from (select distinct m2.col0, m2.col1
from material as m2
) as m2
where m2.col0 = c.col0
) as dcol1,
但是第一个更好的将具有更好的性能。
编辑:
对于这些查询,您需要在(col0, col1)
上建立索引。
答案 1 :(得分:0)
这建议我将GROUP BY
与COUNT(DISTINCT)
一起简单使用:
SELECT Col0, COUNT(DISTINCT Col1) AS DCol1,
COUNT(DISTINCT Col2) AS DCol2, COUNT(DISTINCT Col3) AS DCol3
FROM table t
GROUP BY Col0;
DISTINCT COUNT
不是FUNCTION
,有两件事,一个是FUNCTION
,它是COUNT()
,另一个是DISTINCT
,可以用于唯一性。
您还可以将其与SELECT
语句一起使用,以使整个行变得唯一。
编辑:如果DISTINCT
函数中的COUNT()
不起作用,则使用相关方法:
select distinct c.col0,
(select count(*)
from (select distinct m1.col1
from material as m1
where m1.col0 = m.col0
) as m1
) as dcol1,
(select count(*)
from (select distinct m2.col2
from material as m2
where m2.col0 = m.col0
) as m2
) as dcol2,
(select count(*)
from (select distinct m3.col3
from material as m3
where m3.col0 = m.col0
) as m3
) as dcol3
from material as m;