获取Access

时间:2015-07-08 14:04:34

标签: sql ms-access count distinct

我尝试了countdistinct的所有组合(正确的:)除外)以获得以下示例。

输入:表t1

NAME       |  FOOD
Mary       |  Apple
Mary       |  Banana
Mary       |  Apple
Mary       |  Strawberry
John       |  Cherries

预期产出:

 NAME      |  FOOD
Mary       |  3
John       |  1

N.B。玛丽有两排Apple,但她有3,因为我们在列中有3个不同的值。 我只为她获得了FOOD专栏4,但我需要3 :(

3 个答案:

答案 0 :(得分:1)

select a.name as NAME, a.count(name) as Food 
from 
(SELECT distinct NAME,Food from table)a

答案 1 :(得分:1)

从查询开始,该查询为您提供 NAME FOOD 的独特组合:

SELECT DISTINCT t1.NAME, t1.FOOD
FROM t1

然后,您可以将其用作另一个子查询,您可以GROUP BYCount

SELECT sub.NAME, Count(*) AS [FOOD]
FROM
    (
        SELECT DISTINCT t1.NAME, t1.FOOD
        FROM t1
    ) AS sub
GROUP BY sub.NAME;

答案 2 :(得分:0)

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