如何从同一个表中查找具有不同where条件的多个记录的计数

时间:2012-01-17 15:24:36

标签: ms-access

我有一个像这样的表

ID    | cid   |lightness    | darkness     | color
------|-------|-------------|--------------|---------
1     | 5     |10           | 20           | green
2     | 5     |10           | 08           | green
3     | 5     |10           | 10           | green
4     | 5     |20           | 05           | green
5     | 8     |10           | 20           | red
6     | 8     |10           | 16           | red
7     | 8     |33           | 20           | red
8     | 5     |10           | 10           | green

我想了解以下内容:

  • 颜色有亮度的记录数10
  • 颜色有黑暗的记录数20

所以输出应该是

Color    | lightness   | darkness   | Total
---------|-------------|------------|---------
green    | 4           | 1          | 5
red      | 2           | 2          | 4
Total    | 6           | 3          | 9

我已经尝试了下面的查询,但它没有带来正确的结果。

Select color, sum(lightness), sum(darkness)
from colortable
where cid in (5,8)
and (lightness = 10 or darkness = 20)
Group by color;

2 个答案:

答案 0 :(得分:4)

试试这个:

Select  color,
        sum(iif(lightness = 10, 1, 0)),
        sum(iif(darkness = 20, 1, 0)),
        count(*)
from    colortable
where   cid in (5,8)
Group by color;

这不会给你总计行。某些SQL变体提供“WITH ROLLUP”子句或类似,但不提供Access AFAIK。你可以使用一个联盟:

Select  color,
        sum(iif(lightness = 10, 1, 0)),
        sum(iif(darkness = 20, 1, 0)),
        count(*)
from    colortable
where   cid in (5,8)
Group by color

union

Select  'Totals',
        sum(iif(lightness = 10, 1, 0)),
        sum(iif(darkness = 20, 1, 0)),
        count(*)
from    colortable
where   cid in (5,8)

答案 1 :(得分:1)

将以下SQL保存为新查询 qryBaseCounts

SELECT
    sub.color,
    sub.light_10,
    sub.dark_20,
    light_10+dark_20 AS light_plus_dark
FROM [
        SELECT
            color,
            Sum(IIf(lightness=10,1,0)) AS light_10,
            Sum(IIf(darkness=20,1,0)) AS dark_20
        FROM colortable
        WHERE
            cid In (5,8)
            AND (lightness=10
            OR darkness=20)
        GROUP BY color
    ]. AS sub;

然后您可以在UNION查询中使用qryBaseCounts:

SELECT
    q1.color,
    q1.light_10 AS lightness,
    q1.dark_20 AS darkness,
    q1.light_plus_dark AS [Total]
FROM qryBaseCounts AS q1
UNION ALL
SELECT
    "Total",
    Sum(q2.light_10)
    Sum(q2.dark_20)
    Sum(q2.light_plus_dark)
FROM qryBaseCounts AS q2;

这是使用 colortable 的示例数据的第二个查询的Access 2007输出:

color lightness darkness Total
green         4        1     5
red           2        2     4
Total         6        3     9