简体   繁体   中英

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

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. 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. 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.

The SQL query I am trying to accomplish is this:

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:

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?).

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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