使用唯一字段值对记录进行计数

时间:2018-10-26 14:10:13

标签: sql ms-access

源表

假设我有一个名为MyTable的表,其内容为:

+----------+------+
| Category | Code |
+----------+------+
|    A     | A123 |
|    A     | B123 |
|    A     | C123 |
|    B     | A123 |
|    B     | B123 |
|    B     | D123 |
|    C     | A123 |
|    C     | E123 |
|    C     | F123 |
+----------+------+

我正在尝试计算每个类别唯一的Code值的数量。


所需结果

对于上面的示例,结果将是:

+----------+-------------+
| Category | UniqueCodes |
+----------+-------------+
|    A     |           1 |
|    B     |           1 |
|    C     |           2 |
+----------+-------------+

由于C123对于A是唯一的,D123对于B是唯一的,并且E123F123对于{{1 }}。


我尝试过的东西

我可以使用以下查询获得单个类别(例如C)的结果:

C

但是,虽然我可以对每个类别的查询进行硬编码,但似乎无法构造一个查询来为每个可能的SELECT COUNT(a.Code) AS UniqueCodes FROM ( SELECT MyTable.Code FROM MyTable WHERE MyTable.Category = "C" ) a LEFT JOIN ( SELECT MyTable.Code FROM MyTable WHERE MyTable.Category <> "C" ) b ON a.Code = b.Code WHERE b.Code IS NULL 值进行计算。

这是我尝试过的:

Category

但是,SELECT c.Category, ( SELECT COUNT(a.Code) FROM ( SELECT MyTable.Code FROM MyTable WHERE MyTable.Category = c.Category ) a LEFT JOIN ( SELECT MyTable.Code FROM MyTable WHERE MyTable.Category <> c.Category ) b ON a.Code = b.Code WHERE b.Code IS NULL ) AS UniqueCodes FROM ( SELECT MyTable.Category FROM MyTable GROUP BY MyTable.Category ) c 不在嵌套c.Category查询的范围内定义。

有人可以建议我如何获得期望的结果吗?

4 个答案:

答案 0 :(得分:1)

我将使用NOT EXISTS并进行聚合:

select category, count(*)
from MyTable t
where not exists (select 1 from MyTable t1 where t1.code = t.code and t1.category <> t.category)
group by category;

答案 1 :(得分:1)

您可以使用两种聚合级别:

select minc as category, count(*)
from (select code, min(category) as minc, max(category) as maxc
      from t
      group by code
     ) as c
where minc = maxc
group by minc;

答案 2 :(得分:0)

这也可以:

select category, count(*) from(
    select a.category,  b.count from mytable a join (
        select code, count(category) as count 
        from mytable 
        group by code 
        having count(category) = 1
    ) b on b.code = a.code
) c group by category

答案 3 :(得分:0)

从@isaace的答案中吸取教训,我也想到了-

SELECT MyTable.Category, COUNT(*)
FROM 
    MyTable INNER JOIN 
    (SELECT Code FROM MyTable GROUP BY Code HAVING COUNT(Category) = 1) a 
    ON MyTable.Code = a.Code
GROUP BY MyTable.Category