获取Access中一列中不同值的数量
Get number of different values in a column in Access
我或多或少地尝试了 count
和 distinct
的所有组合(正确的组合除外 :))以获得下面的示例。
输入:tablet1
NAME | FOOD
Mary | Apple
Mary | Banana
Mary | Apple
Mary | Strawberry
John | Cherries
预期输出:
NAME | FOOD
Mary | 3
John | 1
N.B。玛丽有两行苹果,但她有 3 行,因为我们在列中有 3 个不同的值。
我只设法为她在 FOOD 栏中获得 4 个,但我需要 3 个 :(
select a.name as NAME, a.count(name) as Food
from
(SELECT distinct NAME,Food from table)a
从一个查询开始,该查询为您提供 NAME 和 FOOD:
的独特组合
SELECT DISTINCT t1.NAME, t1.FOOD
FROM t1
然后您可以将其用作另一个子查询,您可以在其中使用 GROUP BY
和 Count
:
SELECT sub.NAME, Count(*) AS [FOOD]
FROM
(
SELECT DISTINCT t1.NAME, t1.FOOD
FROM t1
) AS sub
GROUP BY sub.NAME;
select a.name, sum(a.FoodCount) from(
select distinct name,COUNT(food) as FoodCount from #t1 group by name, food ) as a group by a.name order by 2 desc
我或多或少地尝试了 count
和 distinct
的所有组合(正确的组合除外 :))以获得下面的示例。
输入:tablet1
NAME | FOOD
Mary | Apple
Mary | Banana
Mary | Apple
Mary | Strawberry
John | Cherries
预期输出:
NAME | FOOD
Mary | 3
John | 1
N.B。玛丽有两行苹果,但她有 3 行,因为我们在列中有 3 个不同的值。 我只设法为她在 FOOD 栏中获得 4 个,但我需要 3 个 :(
select a.name as NAME, a.count(name) as Food
from
(SELECT distinct NAME,Food from table)a
从一个查询开始,该查询为您提供 NAME 和 FOOD:
的独特组合SELECT DISTINCT t1.NAME, t1.FOOD
FROM t1
然后您可以将其用作另一个子查询,您可以在其中使用 GROUP BY
和 Count
:
SELECT sub.NAME, Count(*) AS [FOOD]
FROM
(
SELECT DISTINCT t1.NAME, t1.FOOD
FROM t1
) AS sub
GROUP BY sub.NAME;
select a.name, sum(a.FoodCount) from(
select distinct name,COUNT(food) as FoodCount from #t1 group by name, food ) as a group by a.name order by 2 desc